简体   繁体   中英

MySql: how to make subquery and count all rows where id is the same in two tables

How to make a query which return values for specific ID's not for all.

    SELECT content.id, count(case likes.type when 'p' then 1 else null end) as p
FROM content
JOIN likes on likes.content_id = content.id

this code returns:

ID p
1 18

but i want it:

ID p
1 12
2 4
3 2

Add a group by

SELECT content.id, 
       sum(likes.type = 'p') as p
FROM content
JOIN likes on likes.content_id = content.id
GROUP BY content.id

Then the aggregate functions (ie count() ) are applied to the groups and not to the whole result.

You query would fail in most databases. The problem is that content.id is not summarized in the select but you are using an aggregation function.

This is a simple problem to fix:

SELECT content.id, count(case likes.type when 'p' then 1 else null end) as p
FROM content
JOIN likes on likes.content_id = content.id
GROUP BY content.id;

However, in general, you should be careful and always include all non-aggregated columns in the select in a group by .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM