0

我正在尝试运行以下查询,但我不断收到语法错误。没有 LEFT JOIN,查询工作正常。如何无错误地实现 LEFT JOIN?

SELECT
    m.mid, 
    m.seq, 
    m.created_on, 
    m.created_by, 
    m.body, 
    r.status,
    u.username_clean
FROM message_recipient r
INNER JOIN message m 
ON m.mid = r.mid AND m.seq = r.seq
WHERE r.uid = ".$logged_in_id." 
AND r.status in ('A', 'N')
AND r.seq = (
             SELECT 
                MAX(rr.seq)
             FROM message_recipient rr
             WHERE rr.mid = m.mid 
             AND rr.status in ('A', 'N')
            )
AND IF (m.seq=1 and m.created_by = ".$logged_in_id." , 1=0, 1=1)
ORDER BY created_on DESC
LEFT JOIN users u 
ON u.user_id = m.created_by
4

1 回答 1

2

LEFT JOIN是在错误的地方。所有的 JOIN 都需要在WHERE子句之前:

SELECT
    m.mid, 
    m.seq, 
    m.created_on, 
    m.created_by, 
    m.body, 
    r.status,
    u.username_clean
FROM message_recipient r
INNER JOIN message m 
  ON m.mid = r.mid AND m.seq = r.seq
LEFT JOIN users u 
  ON u.user_id = m.created_by
WHERE r.uid = ".$logged_in_id." 
  AND r.status in ('A', 'N')
  AND r.seq = (
               SELECT 
                  MAX(rr.seq)
               FROM message_recipient rr
               WHERE rr.mid = m.mid 
               AND rr.status in ('A', 'N')
              )
  AND IF (m.seq=1 and m.created_by = ".$logged_in_id." , 1=0, 1=1)
ORDER BY created_on DESC

SQL 子句按以下顺序排列:

SELECT 
FROM
JOIN
WHERE 
GROUP BY 
ORDER BY

即使您有多个连接,它们也会出现在WHERE

于 2013-03-28T19:44:06.387 回答