![](/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.