2011-12-03 67 views
2

我遇到以下存儲過程查詢問題。 我有3個表:如何讓mySql返回選擇與計數連接?

**table: prop_details** 
prop_id | prop_title 
    1 | sun 
    2 | moon 
    3 | star 
    4 | mars 

**table: prop_account** 
prop_id | acnt_id 
1  | 1 
2  | 1 
3  | 1 
4  | 1 

**table: prop_unit** 
unit_id | prop_id 
    1 | 1 
    2 | 1 
    3 | 1 
    4 | 2 
    5 | 2 
    6 | 3 
    7 | 3 
    8 | 3 

我想收集以下輸出在存儲過程:

prop_id  | prop_title | acnt_id  | unit_count 
     1 | sun   | 1    | 3 
     2 | moon   | 1    | 2 
     3 | star   | 1    | 3 
     4 | mars   | 1    | 0 

這裏是SP我有,但它只返回1行:

PROCEDURE `NewProc`(IN in_acntID int) 
BEGIN 
SELECT 
    *, COUNT(unit_id) AS unitCount 
FROM 
    prop_units pu 
RIGHT JOIN 
    prop_details pd 
ON 
    pu.prop_id = pd.prop_id 
RIGHT JOIN 
    prop_account pa 
ON pd.prop_id = pa.prop_id 
WHERE 
    pa.acnt_id = in_acntID; 
END; 

我打電話的SP像這樣:調用selPropertyByAcntID(@cntID)// @ acntID = 1

回答

2

你的SELECT語句應該是這樣的:

SELECT d.prop_id, d.prop_title, a.acnt_id 
    , SUM(CASE 
      WHEN u.prop_id IS NOT NULL THEN 1 
      ELSE 0 
     END) AS UnitCount 
FROM #prop_details AS d 
INNER JOIN #prop_account AS a ON d.prop_id = a.prop_id 
LEFT JOIN #prop_unit AS u ON d.prop_id = u.prop_id 
GROUP BY d.prop_id, d.prop_title, a.acnt_id 
+0

嗨亞當,感謝您的答覆,但我使用MySQL的,我不相信支持全外連接。 – Rick

+0

@Rick對不起。我已經更新了我的答案以使用「LEFT JOIN」。 –

+0

你的解決方案震撼了它。謝謝! – Rick

0

嘗試添加GROUP BY條款:

PROCEDURE `NewProc`(IN in_acntID int) 
BEGIN 
SELECT 
    *, COUNT(unit_id) AS unitCount 
FROM 
    prop_units pu 
RIGHT JOIN 
    prop_details pd 
ON 
    pu.prop_id = pd.prop_id 
RIGHT JOIN 
    prop_account pa 
ON pd.prop_id = pa.prop_id 
WHERE 
    pa.acnt_id = in_acntID 
GROUP BY pu.prop_id; 
END;