【问题标题】:How to count a null value as 0 while using JOINS in Mysql database?在 Mysql 数据库中使用 JOINS 时如何将空值计为 0?
【发布时间】:2020-12-15 09:20:00
【问题描述】:

我有2张桌子如下

人类

id name
1  John
2  mark 

电脑

id human_id
1  2
2  null

我希望我的回答如下

name no_of_computer
John 0
mark 1

我尝试了以下但错了

select h.name,c.human_id) as 'no_of_computer' from human h
join 
computer c on c.human_id = h.id 
group by h.id

我的代码没有将 null 计为 0,因此它只是避免了这种情况,只显示该标记有 1 台计算机,但我想看到 John 也有 0 台计算机。请帮帮我,在此先感谢

【问题讨论】:

  • 试试LEFT加入
  • 您发布的代码在语法上不正确,请更正。以及 p.id 来自哪里?

标签: mysql database join count null


【解决方案1】:

您可以使用类似于以下内容的子查询:

SELECT  
h.Name,
(SELECT COUNT(c.id_of_computers) 
FROM computers c
WHERE c.id_human = h.id) as no_of_computer
FROM humans h

不要剪切和粘贴这个来测试,因为我没有注意你表中的实际 ID 名称。你得看看那个。 ?

【讨论】:

    猜你喜欢
    • 2013-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多