假设我在PostgreSQL中有这两个表。
TABLE "Likes" (
id,
post-id (foreign key pointing to "Post" table)
)
TABLE "Post" (
id,
body,
date
)
我想要做的是获取所有帖子和每个帖子的喜欢数量。
我写了这个查询:
SELECT "post-id", COUNT(*) AS "likes" FROM "Likes"
GROUP BY "post-id";
将返回以下内容:
-------------------
| post-id | likes |
-------------------
| 1 | 9 |
-------------------
| 4 | 2 |
-------------------
但我仍然需要将此查询与获取有关帖子的所有信息的查询合并...所以最后,我想要这样的事情:
---------------------------------------------------
| id | likes | body | date |
---------------------------------------------------
| 1 | 9 | This is a post! | 2017-05-03 |
---------------------------------------------------
| 2 | | Tasdasdas! | 2017-05-03 |
---------------------------------------------------
| 4 | 2 | This is another post! | 2017-05-04 |
---------------------------------------------------
| 5 | | ssdasdasdadadass | 2017-05-04 |
---------------------------------------------------
我的问题是,我不知道如何添加"喜欢"获取所有帖子的查询列,因为只有某些帖子喜欢。
提前致谢! ^ _ ^
答案 0 :(得分:2)
您想要的是LEFT JOIN
的典型案例:
SELECT post.*, COUNT(likes.id) likes
FROM post
LEFT JOIN likes ON post.id = likes.post_id
GROUP BY post.id
这样,您可以SELECT post.*
,因为GROUP BY post.id
意味着functional dependency。
Sidenote :您的标识符名称非常奇怪。您应该尽量避免引用标识符,这只会让您的查询更难阅读。
答案 1 :(得分:1)
Select p.id, c."likes", p.body, p.date
from Posts p
left join
(
SELECT "post-id", COUNT(*) AS "likes" FROM "Likes"
GROUP BY "post-id"
) c on p.id = c."post-id";