MySQL - 在同一查询中使用多个LEFT JOIN语句

时间:2014-08-26 16:04:28

标签: php mysql sql left-join

我正在尝试使用MySQL从乘法表中选择数据。因此我使用LEFT JOIN。虽然我无法正确理解陈述。

这是我的代码:

$stmt = $dbh->prepare("
            SELECT ur.title, ur.forum_id, urs.*
            FROM forum_topics as ur 
              LEFT JOIN forum_cats as urs 
              ON ur.forum_id=urs.forum_id 
            WHERE ur.topic_id=:topicid
              LEFT JOIN forum_posts as pos
            WHERE pos.post_id=:post



            "
         );
    $stmt->bindParam(':topicid',$postData['topic_id']);
    $stmt->bindParam(':post', $post);
    $stmt->execute();
    $topicData = $stmt->fetch();

这是我的错误消息:

<b>Fatal error</b>:  Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LEFT JOIN forum_posts as pos
WHERE pos.post_id='5886'
' at line 6' .php</b> on line <b>82</b><br />

所以,我的问题是:我的MySQL查询出了什么问题?

2 个答案:

答案 0 :(得分:1)

您应该使用一个WHERE条件,并在第二个联接中使用ON指定加入条件:

SELECT 
  ur.title, 
  ur.forum_id, 
  urs.*
FROM forum_topics as ur 
LEFT JOIN forum_cats as urs 
  ON ur.forum_id=urs.forum_id 
LEFT JOIN forum_posts as pos
  ON (... condition ...)
WHERE ur.topic_id=:topicid
  AND pos.post_id=:post

注意我遗漏了连接条件,因为问题不清楚,我猜想你想在AND子句中使用WHERE,如果需要,你可以切换到OR。 / p>

答案 1 :(得分:0)

在所有连接后,在所有连接的表上使用WHERE。在所有联接上使用ONUSING

USING是一个很好的速记,两个表中的列名称相同。它不仅更短,而且还删除了重复的列,并且在这种情况下,可以使用没有表前缀的列forum_id。

像这样:

SELECT ur.title, 
       ur.forum_id, 
       urs.*
  FROM forum_topics as ur 
  LEFT JOIN forum_cats as urs 
       USING (forum_id)
  LEFT JOIN forum_posts as pos
       USING (forum_id)
 WHERE pos.post_id=:post
   AND topic_id=:topicid