我有两张桌子:
Employers:
id_employe, id_department, city_empl
1, 2, Barcelona
2, 2, Barcelona
3, 1, Madrid
4, null, Sevilla
Departaments:
id_departament, city_dpt
1, Barcelona
2, Bilbao
3, Madrid
我首先需要的是获得两个表格和每个城市中所有不同的城市,我必须列出有多少雇主在那里工作。
因此,我的查询应返回类似于:
的内容Barcelona, 2
Madrid, 1
Sevilla, 1
Bilbao, 0/null
我尝试使用UNION获取所有城市,然后为每个UNION结果行选择一个employees表,但由于UNION查询返回的多个结果,SQL不允许这样做。 / p>
有什么想法吗?
答案 0 :(得分:0)
试试这个:
SELECT City, SUM(id_employe IS NOT NULL) AS Num FROM (
SELECT city_empl AS City, id_employe
FROM Employers
UNION ALL
SELECT city_dpt AS City, null AS id_employe
FROM Departaments
) AS intbl
GROUP BY City