使用左外连接找不到记录时返回0而不是NULL

时间:2017-10-16 11:43:17

标签: mysql join count outer-join

我有两张桌子。我的查询应该返回以下内容:

AUT  | 0

但它不会返回任何内容。试过以下,但没有任何作用。

select substr(s.initial_group_code,1,3) as ko_tun, ifnull(count(s.id),0) 
from study_entitlement s
left outer join graduation_status g on g.study_entitlement_id = s.id
where g.graduation_status_date between str_to_date('01.01.2017', '%d.%m.%Y') 
  and str_to_date('31.01.2017', '%d.%m.%Y')
and substr(s.initial_group_code,1,3) = 'AUT'
group by substr(s.initial_group_code,1,3);
select substr(s.initial_group_code,1,3) as ko_tun, count(s.id)+0 
from study_entitlement s
left outer join graduation_status g on g.study_entitlement_id = s.id
where g.graduation_status_date between str_to_date('01.01.2017', '%d.%m.%Y') 
  and str_to_date('31.01.2017', '%d.%m.%Y')
and substr(s.initial_group_code,1,3) = 'AUT'
group by substr(s.initial_group_code,1,3);
select substr(s.initial_group_code,1,3) as ko_tun, COALESCE(count(s.id),0) 
from study_entitlement s
left outer join graduation_status g on g.study_entitlement_id = s.id 
where substr(s.initial_group_code,1,3) = 'AUT'
and g.graduation_status_date between str_to_date('01.01.2017', '%d.%m.%Y') 
  and str_to_date('31.01.2017', '%d.%m.%Y')
group by substr(s.initial_group_code,1,3);

2 个答案:

答案 0 :(得分:0)

一般来说,因为你的代码很混乱:

SELECT
    TblA.column1,
    TblA.column2,
    TblB.column3
FROM
    a AS TblA
LEFT JOIN
    b AS TblB
    ON TblA.column4 = TblB.column4

如果表格未加入(或NULL中的值为column3),则column3会导致NULL

因此,您可以添加IF语句来更改:

SELECT
    TblA.column1,
    TblA.column2,
    IF(TblB.column3 IS NULL, 0, TblB.column3) AS column3
FROM
    a AS TblA
LEFT JOIN
    b AS TblB
    ON TblA.column4 = TblB.column4

其中说"如果column3为null,则将其设置为0,否则返回列值。"

答案 1 :(得分:0)

您需要将外部表上的过滤条件从WHERE子句移动到连接的ON子句。否则,您将隐式转换为INNER JOIN

这样的事情对你有用:

select substr(s.initial_group_code,1,3) as ko_tun, 
  count(g.study_entitlement_id)
from study_entitlement s
left outer join graduation_status g on g.study_entitlement_id = s.id 
  and g.graduation_status_date between str_to_date('01.01.2017', '%d.%m.%Y') 
    and str_to_date('31.01.2017', '%d.%m.%Y')
where substr(s.initial_group_code,1,3) = 'AUT'
group by substr(s.initial_group_code,1,3);