我收到这个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";
非常感谢您的帮助。谢谢。
答案 0 :(得分: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
列表中,如果您希望0
s NULL
s而不发表评论的帖子,请将comments.total_comments,
更改为:
COALESCE(comments.total_comments, 0) AS total_comments,