【问题标题】:sql select count with group, add null value if no result foundsql select count with group,如果没有找到结果,则添加空值
【发布时间】:2017-03-15 08:14:41
【问题描述】:

我有三个表,我想用另一个表列中的组来计算每一行。
问题是未找到记录时,组计数将不返回任何内容。
所以我想为没有找到记录的每个组添加空值。

这里是查询:

select monster.monster_name,count(*) as count
from monster right join monster_ability 
on monster.monster_id= monster_ability.monster_id  where    
isnull(monster_ability.used) 
group by monster.monster_id

这里是小提琴:fiddle

我希望结果应该是这样的:

| monster_name | count |
|--------------|-------|
|         kora |     1 |
|      lowdowu |     3 |
|      ngjengeh|   null|
|       lortyu |     1 |
|     foh du fy|   null|

【问题讨论】:

    标签: mysql


    【解决方案1】:

    当count为0时,使用case when获取null:

    select
        m.monster_name,
        case when count(a.ability_id) = 0 then null else count(a.ability_id) end as `count`
    from monster m
    left join monster_ability ma on m.monster_id = ma.monster_id and ma.used is null
    left join ability a on ma.ability_id = a.ability_id
    group by m.monster_id
    

    SQLFiddle demo 在这里。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-28
      • 1970-01-01
      • 1970-01-01
      • 2015-12-15
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      相关资源
      最近更新 更多