如何在包含 JOIN 的查询中使用 ORDER BY?

How to use ORDER BY in a query which is containing JOIN?

我有一个查询,它为每个 post 选择所有评论。这是我的查询:

SELECT c.id, c.content, u.name, u.reputation, SUM(v.value) AS total_vote_comments
FROM comments c
INNER JOIN users u ON c.user_id = u.id
LEFT JOIN votes_comments v ON c.id = v.comment_id
WHERE c.post_id = :id;

现在我想将 ORDER BY c.id 添加到该查询。怎么样?

你可以在末尾添加 ORDER BY 子句:

SELECT c.id, c.content, u.name, u.reputation, SUM(v.value) AS total_vote_comments
FROM comments c
INNER JOIN users u ON c.user_id = u.id
LEFT JOIN votes_comments v ON c.id = v.comment_id
WHERE c.post_id = :id
ORDER BY c.id;

一个 order by 是不相关的,因为这个查询 returns 一行:

SELECT c.id, c.content, u.name, u.reputation, SUM(v.value) AS total_vote_comments
FROM comments c INNER JOIN
     users u
     ON c.user_id = u.id LEFT JOIN
     votes_comments v
     ON c.id = v.comment_id
WHERE c.post_id = :id;

这是一个没有 GROUP BY 的聚合查询(因为 SUM())。这样的查询 总是 returns 一行,即使没有行匹配连接。

您可能想要 GROUP BY。我最好的猜测是:

SELECT c.id, c.content, u.name, u.reputation, SUM(v.value) AS total_vote_comments
FROM comments c INNER JOIN
     users u
     ON c.user_id = u.id LEFT JOIN
     votes_comments v
     ON c.id = v.comment_id
WHERE c.post_id = :id
GROUP BY c.id, c.content, u.name, u.reputation
ORDER BY c.id;

通过使用此查询,您只会获得您在 where 子句中输入了 id 的一行。 如果您想订购一个 post,那么您可以在最后写 order by。 如果您想首先获得最后的评论,请使用 desc 和 order by。

SELECT c.id, c.content, u.name, u.reputation, SUM(v.value) AS total_vote_commentFROM 评论 c INNER JOIN 用户 u ON c.user_id = u.id LEFT JOIN votes_comments v ON c.id = v.comment_id WHERE c.post_id = :id按 id desc 排序;

desc = 降序
asc = 升序