dousong1992 2012-07-01 23:24
浏览 133
已采纳

我认为与LEFT JOIN有关的SQL语法错误?

I am receiving this mysql error and i don't know why. I am following a tutorial and i have copied the syntax from the video word for word. Can anybody spot whats wrong?

Here is the error:

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 ( SELECT post_id, COUNT(comment_id) AS `total_co' at line 11

     $query = "SELECT 
        `posts`.`post_id`                 AS `id`,
        `posts`.`post_title`              AS `title`,
         LEFT(`posts`. `post_body`, 512)  AS `preview`,
        `posts`.`post_user`               AS `user`,
         DATE_FORMAT(`posts`.`post_date`, '%d/%m/%Y %H:%i:%s') AS `date`,
         `comments`.`total_comments`,
        DATE_FORMAT(`comments`.`last_comment`, '%d/%m/%Y %H:%i:%s') AS `last_comment`

         FROM `posts`, 
         LEFT JOIN (
            SELECT 
                `post_id`,
                COUNT(`comment_id`) AS `total_comments`,
                MAX(`comment_date`) AS `last_comment`
            FROM `comments`
            GROUP BY `post_id` 
         ) AS `comments`
         ON `posts`.`post_id` = `comments`.`post_id` 
         ORDER BY `posts`.`post_date` DESC";

Your help is much appreciated. Thank you.

  • 写回答

1条回答 默认 最新

  • dongyi5070 2012-07-01 23:26
    关注

    Remove the comma , at line 10:

    FROM `posts`
         LEFT JOIN 
    

    The correct syntax is:

    FROM  
        <table a>
      LEFT JOIN  
        <table b>
          ON  <join condition>
    

    Unrelated to the problem:

    • For a (small) improvement on efficiency, change the COUNT(comment_id) to:

              COUNT(*) AS total_comments,
      
    • You could also add a (post_id, comment_date) index on table comments

    • In the main SELECT list, if you prefer to have 0s than NULLs for posts without comments, change comments.total_comments, to:

      COALESCE(comments.total_comments, 0) AS total_comments,
      
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示