Oracle SQL-如何从其他表中选择具有0个或多个值的表

时间:2018-11-09 16:41:24

标签: sql oracle select

我需要咨询一下城市的ID,名称以及该城市有多少客户,包括拥有0个客户的城市;

我最初是试图获得那些有客户但对如何将没有客户的城市包括在内的想法。

我有一张桌子:CITIES包含ID_city,NAME和REGION  表格:包含ID_client,NAME和ID_city的CLIENTS

查询:

select l.name, l.ID_city, count(c.name) from clients c
JOIN cities l on l.ID_city = c.ID_city
GROUP BY l.name, l.ID_city;

2 个答案:

答案 0 :(得分:0)

使用left join

select l.nomecidade, l.codcidade, count(c.nomecliente) from prova.clientes c
left  JOIN prova.cidades l on l.codcidade = c.codcidade
GROUP BY l.nomecidade, l.codcidade

答案 1 :(得分:0)

使用左联接,但请确保首先考虑哪个表。 下面的代码应该可以解决问题:

select C1.name, C1.ID_city, count(C2.name) from cities C1
LEFT JOIN clients C2 on C1.ID_city = C2.ID_city
GROUP BY C1.name, C1.ID_city;