我有两个名为 country 和 city 的表,它们是关系表。
表结构:
Country : CountryID CountryName
City : CityID CountryID CityName
其中两个表都包含一些数据。我想要结果哪个国家的城市少于 3 个。
我有两个名为 country 和 city 的表,它们是关系表。
表结构:
Country : CountryID CountryName
City : CityID CountryID CityName
其中两个表都包含一些数据。我想要结果哪个国家的城市少于 3 个。
试试这个
select c.CountryID
from country c
left join city ci on c.CountryID=ci.CountryID
group by c.CountryID
having COUNT(c.CountryID)<3
select c1.CountryName
from country c1 left join city c2 on c1.CountryID=c2.CountryID
group by c2.CountryID,c1.CountryName,c1.CountryID having count(*)<3
SELECT co.CountryID, co.CountryName, COUNT(ci.CityID) as NumberOfCities
FROM Country co
LEFT JOIN City ci
ON
co.CountryID = ci.CountryID
GROUP BY co.CountryID, co.CountryName
HAVING COUNT(ci.CityID) < 3
SQL> select * from country;
CNID CNNAME
--- ----------
ind india
pak pakistan
usa amerika
SQL> select * from city;
CTID CNID CTNAME
---------- --- ----------
11 ind delhi
22 ind mummbai
55 pak lahore
66 pak islamabad
77 pak peshavar
100 usa ny
101 usa ams
102 usa chi
103 usa amaz
9 rows selected.
SQL> with ans as
2 (select cn.cnname, cn.cnid, count(ctid)
3 from country cn, city ct
4 where cn.cnid = ct.cnid
5 group by cn.cnid, cn.cnname
6 having count(ctid)<3)
7 select cnname from ans;
CNNAME
----------
india
SQL>
select *
from country LEFT JOIN
(select CountryID, count(*) as cnt
from city
group by CountryID
having cnt<3) c ON country.CountryID =c.CountryID