1

我收到这个 mysql 错误,我不知道为什么。我正在学习一个教程,并且我已经逐字复制了视频中的语法。任何人都可以发现有什么问题吗?

这是错误:

您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 11 行的 'LEFT JOIN ( SELECT post_id, COUNT( comment_id) AS `total_co'附近使用正确的语法

     $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";

非常感谢您的帮助。谢谢你。

4

1 回答 1

6

删除第 10 行的逗号,

FROM `posts`
     LEFT JOIN 

正确的语法是:

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

与问题无关:

  • 对于效率的(小)改进,将其更改COUNT(comment_id)为:

            COUNT(*) AS total_comments,
    
  • 您还可以(post_id, comment_date)在表上添加索引comments

  • 在主SELECT列表中,如果您更喜欢在没有评论的帖子中使用0s 而不是s,请更改为:NULLcomments.total_comments,

    COALESCE(comments.total_comments, 0) AS total_comments,
    
于 2012-07-01T23:26:08.540 回答