2017-10-16 116 views
-1

我有兩個表。我的查詢應返回以下內容:當使用左外連接未找到記錄時,返回0而不爲NULL

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); 
+0

請與編輯器格式化你的代碼,所以它更容易分不清哪個是哪個。 – kchason

+0

你確定數據集中實際存在「AUT」組嗎?您可能需要在此處使用日曆表的路線。 –

+0

我在這裏看不到問題,因爲您選擇的兩列都在基表中,而不是外連接的表。你的意思是什麼都沒有用?我假設三個查詢都是在同一代碼上的所有不同的嘗試? – kchason

回答

0

一般地,因爲你的代碼是相當混亂:

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

會導致NULLcolumn3地方的表不加入(或column3NULL) 。

因此,你可以添加一個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 

它說,「如果欄3爲空,然後將其設置爲0,否則,返回該列的值。」

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); 
+0

感謝百萬Ike Walker.I實際上在ON條款的開頭部分有過濾標準,但沒有注意到我正在計算錯誤的列。所以再次感謝:) –