douyinbo3361 2014-08-26 16:04
浏览 235
已采纳

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

I am trying to select data from multiply tables using MySQL. Therefore I am using LEFT JOIN. Although I am having trouble getting the statement correct.

This is my code:

$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();

This is my error message:

<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 />

So, my question is: what is wrong with my MySQL Query?

  • 写回答

2条回答 默认 最新

  • doubo1711 2014-08-26 16:09
    关注

    You should use one WHERE condition and specify the join condition with ON in the second join:

    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
    

    Note I left out the join condition since it's not clear from the question and I guessed you wanted an AND in the WHERE clause, you can switch to OR if needed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 电脑蓝屏logfilessrtsrttrail问题
  • ¥20 关于wordpress建站遇到的问题!(语言-php)(相关搜索:云服务器)
  • ¥15 【求职】怎么找到一个周围人素质都很高不会欺负他人,并且未来月薪能够达到一万以上(技术岗)的工作?希望可以收到写有具体,可靠,已经实践过了的路径的回答?
  • ¥15 Java+vue部署版本反编译
  • ¥100 对反编译和ai熟悉的开发者。
  • ¥15 带序列特征的多输出预测模型
  • ¥15 Python 如何安装 distutils模块
  • ¥15 关于#网络#的问题:网络是从楼上引一根网线下来,接了2台傻瓜交换机,也更换了ip还是不行
  • ¥15 资源泄露软件闪退怎么解决?
  • ¥15 CCF-CSP 2023 第三题 解压缩(50%)