SQL相关的棘手计数()查询
问题描述:
我有4个表:SQL相关的棘手计数()查询
country
:
- ID
- 名
region
:
- ID
- 名
- fk_country
dept
:
- ID
- 名
- fk_region
user
:
- ID
- fk_country
- fk_region
- fk_dept
的user
表只有一个外键集(其他应为空)。
我们没有设置外键fk_pays
,因为我们可以通过fk_region.fk_country
通过fk_dept.fk_region.fk_country
触摸country
表(当fk_dept
设置)
OR
(当fk_region
设置)
这种行为是为了避免冗余。
我的问题是:
如何获取与包含用户(COUNT
)在该国号的相加列的所有国家的信息?
我知道如何使用不同的请求为每个支付(使用COALESCE
),但我希望在一个单一的。
答
只需使用或加入
SELECT c.id, c.name, count(DISTINCT u.id)
FROM country AS c
JOIN region AS r ON c.id=r.fk_country
JOIN dept AS d ON r.id=d.fk_region
JOIN users AS u ON u.fk_country=c.id OR u.fk_region=r.id OR u.fk_dept=d.id
GROUP BY c.id,c.name;
答
试试这个:
SELECT count(user.id), country.name, region.name, dept.name FROM user
JOIN country ON user.fk_country = country.id
JOIN region ON region.fk_country = country.id
JOIN dept ON dept.fk_region = region.id
GROUP BY country.id
我没有尝试任何事情,似乎复杂(加入,并加不同'COUNT的'query) – Leto 2013-03-06 12:44:00
'select country。*,count(user.id)from country,user where country.id = user.fk_country group by country.id' – deadlock 2013-03-06 12:53:15
我不是想要做一个简单的'COUNT'查询 – Leto 2013-03-06 13:01:47