0

我有两张桌子:

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 结果行选择雇主表,但 SQL 不允许这样做,因为 UNION 查询返回多个结果。

任何想法 ?

4

1 回答 1

1

尝试这个:

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
于 2013-09-25T16:51:09.587 回答