如何让mySql返回选择JOIN with Count?

时间:2011-12-03 06:52:09

标签: mysql stored-procedures select count inner-join

我遇到以下存储过程查询的问题。 我有3张桌子:

**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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;