如何按其他表中的最新记录对记录进行排序
我想按最近的活动排序(注释)。但是,如果语句没有注释,则下面的查询在最后不会显示该语句。如何更改查询,以便最后显示并显示没有注释的语句?如何按其他表中的最新记录对记录进行排序
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)
尝试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,如果你这样做 ORDER BY ... ASC NULL值首先提出并最后,如果你做的ORDER BY ... DESC。
没有评论的声明(MAX(comments.id) IS NULL
)必须放置在结果的底部。
我已经尝试过。它不起作用。 – user3835276 2014-09-01 20:41:46
@ user3835276,尽量不要使用短语“不起作用”。我们通常认为它是可能的最不有用的错误报告':-)'。考虑这个答案是一个暗示让你去? – halfer 2014-09-01 20:42:25
@halfer了解。 – user3835276 2014-09-01 20:45:12
我会做完全略有不同:
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的组,该查询应在任何其他数据库。
的[在SQL中,如何在表内的字段集合]可能重复(http://stackoverflow.com/questions/10412033/in-sql-how-to-aggregate-on-a-field-inside - 表) – Bulat 2014-09-01 21:11:15