一.业务需求
在两表联查中,一个是字典表:
另外一个业务表:
按字典表的id与业务表的hazard_level_id关联。
查出来的除了 按1,2,3,4分组还有一组无id编号的,即null
也就是要按1,2,3,4,null进行分组。
二.解决办法:
1.在关联的时候,以业务表作左连接表,因为只有这样才能查出为null的数据。如果以那个字典表作为左表,那是只能查出按1234分类的。
2.注意case when的用法:case when h.id is null then 5 else h.id end
表示 如果 h.id的值为空的话,那么h.id的值就取5,否则就取h.id本身。
看结果:
SELECT
(case when h.id is null then 5 else h.id end) as id ,
(case when h.id is null then '无危害等级' else h.description end) as name,
count(b.id) as value
FROM sys_bug b
left JOIN sys_bug_hazard_level h
ON h.id = b.hazard_level_id
group by h.id
查询结果:
这里就查出了 业务表里 hazard_level_id为null的总条数,并且把它设为id为5,name为 无危害等级。