[英]How to select all entries in a table with a subquery counting entries in another table by id from the first query
I have two tables: albums and photos我有两张桌子:相册和照片
albums专辑
id ID | name姓名 | user_id用户身份 |
---|---|---|
1 1 | New Year 2022 2022 年新年 | 2 2 |
2 2 | Birthday Party生日聚会 | 2 2 |
3 3 | Wedding婚礼 | 2 2 |
For every album there are photos in photos table对于每个相册,照片表中都有照片
photos相片
id ID | album_id专辑编号 | name姓名 |
---|---|---|
1 1 | 1 1 | IMG_0754.JPG IMG_0754.JPG |
2 2 | 2 2 | IMG_0764.JPG IMG_0764.JPG |
3 3 | 2 2 | IMG_0654.JPG IMG_0654.JPG |
4 4 | 3 3 | IMG_1254.JPG IMG_1254.JPG |
5 5 | 3 3 | IMG_0054.JPG IMG_0054.JPG |
6 6 | 3 3 | IMG_0004.JPG IMG_0004.JPG |
I need to select all albums by user_id (in this example by user_id 2) from albums table, and count all photos from photos table, so that I get something like我需要 select 从相册表中按 user_id (在本例中按 user_id 2)的所有相册,并计算照片表中的所有照片,这样我就得到了类似的东西
id ID | name姓名 | user_id用户身份 | photo_count照片计数 |
---|---|---|---|
1 1 | New Year 2022 2022 年新年 | 2 2 | 1 1 |
2 2 | Birthday Party生日聚会 | 2 2 | 2 2 |
3 3 | Wedding婚礼 | 2 2 | 3 3 |
Thanks!谢谢!
This is how I would write it with ms-sql.这就是我用 ms-sql 编写它的方式。 You may need to tweak it for postgresql.您可能需要针对 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
I figured out the answer, which is我想出了答案,那就是
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
OK, after the advice of @Sonyck the solution would be好的,在@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.