gpt4 book ai didi

mysql - SQL Count 返回太多行

转载 作者:行者123 更新时间:2023-11-29 04:43:17 25 4
gpt4 key购买 nike

我有以下 SQL 语句:

    SELECT 
O.id,
O.name,
(SELECT
COUNT(U.id)
FROM
User U
WHERE
U.organization_id = O.id) AS num_users
FROM
Organization O

User 表和 Organization 表由一个叫做 organization_id 的东西绑定(bind)

当我执行这条语句时,我得到以下(坏)结果:

id |  name   | num_users
------------------------
1 | MyOrg | 2
2 | MyOrg | 0
3 | testOrg | 0

谁能告诉我如何才能得到只会产生 1 行 pr 的结果。组织?

请注意,我已经尝试使用 DISTINCT 但没有得到更好的结果

最佳答案

SQL Fiddle演示以下查询:

SELECT GROUP_CONCAT(DISTINCT o.id SEPARATOR ', '), O.name, 
COUNT(U.organization_id) AS MyCount
FROM Organization O
LEFT JOIN User U ON U.organization_id = O.id
GROUP BY O.name;

或者,如果您不需要 id 字段,则:

SELECT O.name, COUNT(U.organization_id) AS MyCount
FROM Organization O
LEFT JOIN User U ON U.organization_id = O.id
GROUP BY O.name;

关于mysql - SQL Count 返回太多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24015592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com