如何让 mySql 返回 Select JOIN with Count?

Posted

技术标签:

【中文标题】如何让 mySql 返回 Select JOIN with Count?【英文标题】:How can I get mySql to return Select JOIN with Count? 【发布时间】:2012-01-12 01:28:42 【问题描述】:

我遇到以下存储过程查询的问题。 我有 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

【问题讨论】:

【参考方案1】:

尝试添加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;

【讨论】:

【参考方案2】:

您的选择语句应如下所示:

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

【讨论】:

嗨,亚当,感谢您的回复,但我使用的是 mysql,我认为它不支持完全外连接。 您的解决方案令人震惊。谢谢!

以上是关于如何让 mySql 返回 Select JOIN with Count?的主要内容,如果未能解决你的问题,请参考以下文章

mysql中inner join和outer join有啥区别?

Mysql left join with nested select慢,如何优化

MYSQL LEFT JOIN 将所有数据返回为 NULL

MySql INNER JOIN三表联查性能如何提升

MySQL 数据库中 left outer join 和 left join 啥区别?

DB-MySQL:MySQL 连接的使用