以下两个SQL语句如何带来相同的记录(MySQL):
声明1:
SELECT distinct CountryCD, StateCD, COUNTRY, STATE
FROM cities
where (CountryCD,StateCD) NOT IN (
select distinct CountryCD1,StateCD from states);
声明2:
SELECT distinct CountryCD, StateCD, COUNTRY, STATE
FROM cities
where (CountryCD,StateCD) IN (
select distinct CountryCD1,StateCD from states);
似乎没有一个不能正常工作。它将这些记录带回(select distinct CountryCD1,StateCD from states)
的结果集中。怎么了?
例如,下面的记录是两个结果集的一部分: 美国加州美国加利福尼亚州
答案 0 :(得分:0)
使用负左连接或内连接来实现这些结果。
内部加入:
SELECT DISTINCT c.CountryCD, c.StateCD, c.COUNTRY, c.STATE
FROM Cities c
INNER JOIN States s
ON s.CountryCD = c.CountryCD AND s.StateCD = c.StateCD
负左连接:
SELECT DISTINCT c.CountryCD, c.StateCD, c.COUNTRY, c.STATE
FROM Cities c
LEFT JOIN States s
ON s.CountryCD = c.CountryCD AND s.StateCD = c.StateCD
WHERE s.StateCD IS NULL