2016-08-09 66 views
2

我有以下4個表。MYSQL左連接表選擇數據問題 - 邏輯錯誤

1. DEBATES. 
    [ID, STARTER_PACK_ID] 
2. DEBATE_GROUPS. 
    [ID, DEBATE_ID, STAKEHOLDER_ID] 
3. DEBATE_STAKEHOLDERS. 
    [ID, STARTER_PACK_ID, NAME] 
4. DEBATE_STARTER_PACKS. 
    [ID] 

我想選擇每辯論組,與每一個利益相關者的ID,利益相關者的ID名稱和利益相關方辯論,其中starter_pack_id等於某個值的計數。例如,這些都被顯示,即使計數爲0或空值存在

這樣做的預期結果是如下..

DEBATE_ID | STAKEHOLDER_ID | COUNT(Example) 
------------------------------------------- 
    1    1    2 
    1    2    1 
    1    3    3 
    2    1    4 
    2    2    1 
    2    3    2 

的問題是,它不是」顯示數據庫中尚未使用 的辯論,這正是我所需要的。我應該在下面的代碼中更改什麼來檢索這些信息?

下面是我嘗試...

SELECT 
    a.id, 
    a.name, 
    a.abbreviation, 
    b.debate_id, 
    IF(COUNT(b.stakeholder_id) = 0, 0, COUNT(b.stakeholder_id)) AS total_freq, 
    COUNT(b.stakeholder_id) AS freq 
FROM 
    debate_stakeholders a LEFT JOIN debate_groups b ON b.stakeholder_id = a.id 
GROUP BY 
    a.id, b.debate_id 
HAVING 
    COUNT(*) < 3 
ORDER BY 
    a.id,b.debate_id,b.stakeholder_id 

回答

1
SELECT 
    a.id, 
    a.name, 
    a.abbreviation, 
    d.id, 
    IF(COUNT(b.stakeholder_id) = 0, 0, COUNT(b.stakeholder_id)) AS total_freq, 
    COUNT(b.stakeholder_id) AS freq 
FROM 
    debate_stakeholders a LEFT JOIN debate_groups b ON b.stakeholder_id = a.id 
    RIGHT JOIN debates as d ON b.debate_id = d.id 
GROUP BY 
    a.id, b.debate_id 
HAVING 
    COUNT(*) < 3 
ORDER BY 
    a.id,b.debate_id,b.stakeholder_id