![](/img/trans.png)
[英]Select all entries from a table and the LATEST entries from another “logging” table
[英]How to select all entries in a table with a subquery counting entries in another table by id from the first query
我有两张桌子:相册和照片
专辑
ID | 姓名 | 用户身份 |
---|---|---|
1 | 2022 年新年 | 2 |
2 | 生日聚会 | 2 |
3 | 婚礼 | 2 |
对于每个相册,照片表中都有照片
相片
ID | 专辑编号 | 姓名 |
---|---|---|
1 | 1 | IMG_0754.JPG |
2 | 2 | IMG_0764.JPG |
3 | 2 | IMG_0654.JPG |
4 | 3 | IMG_1254.JPG |
5 | 3 | IMG_0054.JPG |
6 | 3 | IMG_0004.JPG |
我需要 select 从相册表中按 user_id (在本例中按 user_id 2)的所有相册,并计算照片表中的所有照片,这样我就得到了类似的东西
ID | 姓名 | 用户身份 | 照片计数 |
---|---|---|---|
1 | 2022 年新年 | 2 | 1 |
2 | 生日聚会 | 2 | 2 |
3 | 婚礼 | 2 | 3 |
谢谢!
这就是我用 ms-sql 编写它的方式。 您可能需要针对 postgresql 对其进行调整。
SELECT a.id, a.name, a.user_id, count(*) as photo_count
FROM ALBUMS a
INNER JOIN PHOTOS p on a.id = p.id
GROUP BY a.id, a.name, a.user_id
我想出了答案,那就是
select albums.id, albums.name, albums.user_id,(select count(*) from photos where photos.album_id = albums.id) as photo_count from albums where user_id = 2
好的,在@Sonyck 的建议之后,解决方案是
SELECT albums.id, albums.name, albums.user_id, count(*) as photo_count
FROM albums
JOIN photos ON (photos.album_id = albums.id)
WHERE user_id = 2
GROUP BY albums.id, albums.name, albums.user_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.