根据另一个表中的2个条件计算mysql表行

时间:2016-10-22 14:17:46

标签: php mysql

我有两张表table1table2table1idtable2_id,而table2idcategory。我需要根据table1中包含值table2.categoryRegular的两个单独值来计算来自Special的行。

我在两个查询中完成了这个,但我想知道是否可以在单个sql中完成。我的疑问是:

"SELECT COUNT(t1.id) AS regular FROM table1 t1 LEFT OUTER JOIN table2 t2 ON t1.t2_id = t2.id WHERE t2.category = 'Regular'";
"SELECT COUNT(t1.id) AS special FROM table1 t1 LEFT OUTER JOIN table2 t2 ON t1.t2_id = pr.id WHERE t2.category = 'Special'";

感谢。

修改

第二个查询JOIN应该是ON t1.t2_id = t2.id而不是ON t1.t2_id = pr.id。很抱歉可能造成的混乱。请相应地更新/编辑您的答案/评论。

2 个答案:

答案 0 :(得分:3)

Where条件移至CASE语句并执行计数

以下是使用Conditional Aggregate

的一种方法
SELECT
COUNT(case when t2.category = 'Regular' then t1.id end) AS Regular,
COUNT(case when t2.category = 'Special' then t1.id end) AS special 
FROM table1 t1 
INNER JOIN table2 t2 ON t1.t2_id = pr.id 
Where t2.category IN ('Regular','Special' )

注意:我已将LEFT JOIN更改为INNER JOIN,因为您只想在table2.category'Regular'或{{1}时进行计数所以不要在这里使用'Special'

答案 1 :(得分:0)

而不是

"SELECT COUNT(t1.id) AS regular FROM table1 t1 LEFT OUTER JOIN table2 t2 ON t1.t2_id = t2.id WHERE t2.category = 'Regular'";
"SELECT COUNT(t1.id) AS special FROM table1 t1 LEFT OUTER JOIN table2 t2 ON t1.t2_id = pr.id WHERE t2.category = 'Special'";

你可以这样做:

select t2.category, count(t1.id)
from table1 t1
left outer join table2
on t1.t2_id = t2.id
group by t2.category
having t2.category in ('Regular', 'Special')

建议的查询对已连接的记录进行分组,过滤组并选择类别名称及其计数。