一页上显示多个COUNT(*)

时间:2017-10-22 09:57:12

标签: php mysql

这可能非常简单 - 但我正在撕裂我的头发。 数据库正在使用cPanel(MariaDB 10.1.28)

继承人的情景

  • 1表被称为"警告"
  • 1列名为" WARNING_REASON" (VARCHAR) warning_reason包含各种"原因"

  • 1列名为" WARNING_LEVEL" (VARCHAR) 它包含" VERBAL"," LEVEL 1"或" LEVEL 2"

我需要在5列表格中的php中输出这些数据

  • 警告原因
  • 以warning_reason
  • 分组的表格中的总行数
  • 匹配" VERBAL"的行总数按warning_reason分组
  • 匹配" LEVEL 1"按warning_reason分组
  • 匹配" LEVEL 2"按warning_reason分组

2 个答案:

答案 0 :(得分:2)

您可以使用子查询来完成此任务:

SELECT t1.warning_reason
, (SELECT COUNT(*) FROM warnings s1 WHERE s1.warning_reason = t1.warning_reason) AS total_count
, (SELECT COUNT(*) FROM warnings s2 WHERE s2.warning_reason = t1.warning_reason AND s2.warning_level = \'VERBAL\') AS verbal_count
, (SELECT COUNT(*) FROM warnings s3 WHERE s3.warning_reason = t1.warning_reason AND s3.warning_level = \'LEVEL 1\') AS level1_count
, (SELECT COUNT(*) FROM warnings s4 WHERE s4.warning_reason = t1.warning_reason AND s4.warning_level = \'LEVEL 2\') AS level2_count
FROM warnings t1
GROUP BY t1.warning_reason

答案 1 :(得分:1)

您可以使用条件聚合

select warning_reason,
    count(*) as total_warnings,
    sum(warning_level = 'VERBAL')  as verbal_warnings,
    sum(warning_level = 'LEVEL 1') as level1_warnings,
    sum(warning_level = 'LEVEL 2') as level2_warnings
from warnings
group by warning_reason

这比运行多个子选择更短,可能更快。

请注意,在MySQL类似warning_level = 'VERBAL'的布尔表达式中,返回10(如果NULL,则返回warning_level is NULL

如果您需要符合标准的查询,可以将行更改为

sum(case when warning_level = 'VERBAL' then 1 else 0 end) as verbal_warnings,

sum(case warning_level when 'VERBAL' then 1 else 0 end) as verbal_warnings,

count(case warning_level when 'VERBAL' then 1 else null end) as verbal_warnings,

因为NULL是ELSE的默认值,你也可以跳过它

count(case warning_level when 'VERBAL' then 1 end) as verbal_warnings,

以下内容也适用于MySQL,但我不确定其他系统是否会以相同的方式对其进行评估:

count(warning_level = 'VERBAL' or null) as verbal_warnings,