加入 mySQL table 和总和 select
Joining a mySQL table with a sum select
我想知道是否有任何方法可以合并这两个查询:
SELECT posts.post_id, posts.member_id, posts.content, posts.date_created, votes.votes
FROM posts
LEFT JOIN votes
ON posts.post_id=votes.post_id
ORDER BY votes.votes;
SELECT post_id, SUM(votes) AS votes_total FROM votes GROUP BY post_id;
我试过这样做,但它只是计算了所有帖子的总票数,而不是每个帖子:
SELECT posts.post_id, posts.member_id, posts.content, posts.date_created, SUM(votes) AS votes_total
FROM posts
LEFT JOIN votes
ON posts.post_id=votes.post_id
ORDER BY votes.votes;
有什么想法吗?
你只需要一个GROUP BY
:
SELECT p.post_id, p.member_id, p.content, p.date_created,
SUM(v.votes) AS votes_total
FROM posts p LEFT JOIN
votes v
ON p.post_id = v.post_id
GROUP BY post_id
ORDER BY votes_total;
通常,您希望 SELECT
中不是聚合函数参数的所有列也位于 GROUP BY
:
中
GROUP BY p.post_id, p.member_id, p.content, p.date_created
不过,在这种情况下,post_id
(大概)是 posts
中的主键。因此,所有其他列在聚合中都是多余的。
我想知道是否有任何方法可以合并这两个查询:
SELECT posts.post_id, posts.member_id, posts.content, posts.date_created, votes.votes
FROM posts
LEFT JOIN votes
ON posts.post_id=votes.post_id
ORDER BY votes.votes;
SELECT post_id, SUM(votes) AS votes_total FROM votes GROUP BY post_id;
我试过这样做,但它只是计算了所有帖子的总票数,而不是每个帖子:
SELECT posts.post_id, posts.member_id, posts.content, posts.date_created, SUM(votes) AS votes_total
FROM posts
LEFT JOIN votes
ON posts.post_id=votes.post_id
ORDER BY votes.votes;
有什么想法吗?
你只需要一个GROUP BY
:
SELECT p.post_id, p.member_id, p.content, p.date_created,
SUM(v.votes) AS votes_total
FROM posts p LEFT JOIN
votes v
ON p.post_id = v.post_id
GROUP BY post_id
ORDER BY votes_total;
通常,您希望 SELECT
中不是聚合函数参数的所有列也位于 GROUP BY
:
GROUP BY p.post_id, p.member_id, p.content, p.date_created
不过,在这种情况下,post_id
(大概)是 posts
中的主键。因此,所有其他列在聚合中都是多余的。