mysql简化查询,不需要子查询

xyhw6mcr  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(337)

在我的数据库中,我存储了错误:

+----+---------------------+----------+-------------------+
| id | date                | message  | name              |
+----+---------------------+----------+-------------------+
|  2 | 2018-07-17 11:01:52 | message2 | TypeError         |
|  1 | 2018-07-14 11:01:52 | message  | HttpErrorResponse |
|  3 | 2018-07-19 11:01:52 | message3 | HttpErrorResponse |
|  4 | 2018-07-19 11:01:52 | message4 | UriError          |
+----+---------------------+----------+-------------------+

我想创建另一个包含每日raports的表:

+-------------+-------------+-------------------+
| day         | htttpErrors | TypeErrors        |OtherErrors:
+---------------------+----------+--------------+
| 2018-07-17  | 1           | 3                 |     0
| 2018-07-18  | 2           | 0                 |     5

如何以最好的方式去做?当然我可以这样做:

SELECT  
    current_date(), 
    (select count(*) from error where day=current_date() and name=TypeErrors)
.........
    FROM error

但有更干净的方法吗?
顺便说一句,不好意思,我不知道该怎么称呼它。

fjnneemd

fjnneemd1#

您可以使用下面这样的sql。

select  date(`date`) as day,
        sum(case when upper(name) like '%HTTP%' then 1 else 0 end) http_errors,
        sum(case when upper(name) like '%TYPE%' then 1 else 0 end) type_errors,
        sum(case when upper(name) not like '%HTTP%' and upper(name) not like '%TYPE%' then 1 else 0 end) other_errors, 
from error group by date(`date`);

相关问题