我需要一个SQL查询,它从三个表中读取(公司,权利A,权利B)。权利A和B是m:n关系的表。我想计算连接到公司的权利A和B中的条目。
公司结构:
CID | Name | ...
权利结构A
RIDe | CID | ...
权利B的结构
RIDu | CID | ...
这是我当前的SQL语句。我有时得到正确的值,但有时不是。我不知道为什么。
SELECT
company.*,
count(rightsa.RIDe) AS AnzahlE,
count(rightsb.RIDu) AS AnzahlU
FROM company
LEFT JOIN rightsa ON company.CID = rightsa.CID
LEFT JOIN rightsb ON company.CID = rightsb.CID
GROUP BY company.CID ORDER BY company.name;
答案 0 :(得分:3)
在计数功能中使用DISTINCT
,因此每个公司只计算不同的rightsa.RIDe
和rightsb.RIDu
SELECT company.*,
count(DISTINCT rightsa.RIDe) AS AnzahlE,
count(DISTINCT rightsb.RIDu) AS AnzahlU
FROM company
LEFT JOIN rightsa ON company.CID = rightsa.CID
LEFT JOIN rightsb ON company.CID = rightsb.CID
GROUP BY company.CID ORDER BY company.name;
答案 1 :(得分:1)
count()
与其他聚合函数的不同之处在于null
值包含 :大多数聚合函数排除 null
对于带有select
子句的group by
语句,结果集中的每一列必须是SQL标准中的一个
根据SQL标准,其他任何东西充其量都是未定义的行为:您依赖于特定SQL实现的变幻莫测。
尝试这样的事情:
select c.* ,
coalesce( a.cnt , 0 ) as AnzahlE ,
coalesce( b.cnt , 0 ) as AnzahlU
from company c
left join ( select CID, count(*) as cnt from rightsa group by CID ) a
left join ( select CID, count(*) as cnt from rightsb group by CID ) b
order by c.name
您可能还会考虑使用相关的子选择来更好地表达您的意图:
select c.*
(select count(*) from rightsa a where a.CID = c.CID) as AnzahlE ,
(select count(*) from rightsb b where b.CID = c.CID) as AnzahlU
from company c
order by c.Name