我的网络应用中有帖子,评论和喜欢。我想通过“得分”来订购帖子,这只是喜欢和评论的总和。
我正在尝试做这样的事情:
SELECT posts.id, COUNT(comments.id) AS c, COUNT(likes.id) AS l
FROM posts
LEFT JOIN comments ON posts.id = comments.post_id
LEFT JOIN likes ON posts.id = likes.post_id
GROUP BY posts.id
ORDER BY SUM(c,l) desc;
但是我收到关于列c不存在的错误;
或者这个:
SELECT posts.id, sum(count(comments.id), count(likes.id)) AS score
FROM posts
LEFT JOIN comments ON posts.id = comments.post_id
LEFT JOIN likes ON posts.id = likes.post_id
GROUP BY posts.id
ORDER BY score desc;
但我收到有关名称和参数类型的错误。
是否有不同的方式来编写此查询以使其有效?谢谢!
答案 0 :(得分:2)
你在大致正确的轨道上,但出于某种原因,你试图使用简单加法的sum
聚合内容:
SELECT posts.id, count(comments.id) + count(likes.id) AS score
FROM posts
LEFT JOIN comments ON posts.id = comments.post_id
LEFT JOIN likes ON posts.id = likes.post_id
GROUP BY posts.id
ORDER BY 2 desc;
我在这里使用了序数位置排序顺序,即按第二列排序。