简体   繁体   English

MySql:如何进行子查询并计算两个表中ID相同的所有行

[英]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. 如何进行查询,而不是全部返回特定ID的值。

    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 添加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. 然后将聚合函数(即count() )应用于组,而不是整个结果。

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. 问题是在select未汇总content.id ,但是您正在使用聚合函数。

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 . 然而,在一般情况下,你要小心, 总是包含在所有的非聚集列select一个在group by

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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