我正在尝试按最近的活动(评论)订购报表。但是,如果某个陈述没有评论,则以下查询不会在结尾处显示该陈述。如何更改查询,因此最后会显示并显示没有注释的语句?
SELECT
`statements`.`id`,
`statement`,
`statements`.`timestamp`,
`statements`.`published`,
`image`,
`statements`.`author_id`,
`statements`.`ip_address`,
`username`,
`comment_count`
FROM
(`statements`)
INNER JOIN `comments`
ON `comments`.`statement_id` = `statements`.`id`
LEFT JOIN `users`
ON `users`.`id` = `statements`.`author_id`
WHERE `statements`.`published` > 0
GROUP BY `statements`.`id`
ORDER BY MAX(comments.id)
答案 0 :(得分:3)
对LEFT JOIN
表:
comments
SELECT `statements`.`id`, `statement`, `statements`.`timestamp`, `statements`.`published`, `image`, `statements`.`author_id`, `statements`.`ip_address`, `username`, `comment_count`
FROM (`statements`)
LEFT JOIN `comments` ON `comments`.`statement_id` = `statements`.`id`
LEFT JOIN `users` ON `users`.`id` = `statements`.`author_id`
WHERE `statements`.`published` > 0
GROUP BY `statements`.`id`
ORDER BY MAX(comments.id) DESC
按最大评论ID降序排序会将最近评论的语句放在最上面。
关于MySQL文档 Working with NULL Values
执行ORDER BY时,如果您这样做,则首先显示NULL值 ORDER BY ... ASC,如果你按照ORDER BY ... DESC进行操作。
没有注释的语句(MAX(comments.id) IS NULL
)必须放在结果的底部。
答案 1 :(得分:0)
我会完全略有不同:
SELECT
statements.*,
cm.id
FROM
statements LEFT JOIN
(SELECT statement_id, MAX(id) id FROM comments GROUP BY statement_id) cm
ON cm.statement_id = statements.id
LEFT JOIN users
ON users.id = statements.author_id
WHERE statements.published > 0
ORDER BY cm.id;
通过这种方式,您不依赖于MySQL组,并且此查询应该可以在任何其他数据库中使用。