简体   繁体   English

如何 select 表中的所有条目,其中子查询按第一个查询中的 id 计数另一个表中的条目

[英]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.

相关问题 从一个表中选择所有条目,并从另一个“日志”表中选择“最新”条目 - Select all entries from a table and the LATEST entries from another “logging” table 从一个表中选择所有条目,在另一个表中有两个特定条目 - Select all entries from one table which has two specific entries in another table SQL筛选器条目与另一个表中的所有条目匹配 - SQL filter entries which match all entries from another table 选择表中所有条目的更新表 - Update table for all entries from select statement 如何从另一个相关表中选择最后2个条目 - How to select the last 2 entries from another related table JOOQ:select 其他表中不存在 ID 的所有表条目 - JOOQ : select all table entries where ID not present in other table 如何将由联接的子查询(与主表ID相关)返回的所有条目串联到单个组合列中? - How to concatenate all entries returned by a joined subquery (related to the main table id) into a single combined column? 计算第二个表中与第一个表中的ID相匹配的条目 - Count entries from second Table that match id from first Table 如何通过ID查询数据库中的所有条目? - How to query all entries from the database by id? 嵌套SQL查询,其中一个表中的ID与另一个存在两个特定条目的表匹配 - Nested SQL Query where id from one table matches to another table where two specific entries exist
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM