以下两个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);


似乎NOT IN不能正常工作。它将这些记录带回到(select distinct CountryCD1,StateCD from states)的结果集中。怎么了?

例如,下面的记录是两个结果集的一部分:
US CA美国加利福尼亚

最佳答案

使用否定的左联接或内部联接可实现这些结果。

内部联接:

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

关于mysql - 选择和不输入如何带来相同的记录?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26347304/

10-12 22:51