SQL连接单个表,其中值不存在

时间:2016-05-05 19:24:15

标签: sql

虽然我无法得到正确答案,但我尝试了很多技巧。 例如,我有一个国家名称和ID的表。而且我想只返回没有使用ID 3的不同国家/地区。因为如果他们在ID 2或1等上被提及,他们仍然会显示我不想要的内容。

SELECT DISTINCT test.country, test.id
FROM test
WHERE test.id LIKE 2
AND test.id NOT IN (SELECT DISTINCT test.id FROM test WHERE test.id LIKE 3);

4 个答案:

答案 0 :(得分:1)

我现在确定我理解了你的问题,但是如果你想要id不是3的不同国家,你只需要这个:

select distinct c.name from Countries
where c.id <> 3

答案 1 :(得分:1)

您希望消除身份证号为3的国家/地区,而不是身份证号码本身......

SELECT Distinct t.country, T.ID
FROM test t
where not exists 
   (Select 1 from test t2 where t2.country = t.country and ID = 3)

或者

SELECT DISTINCT test.country, test.id
FROM test
WHERE test.country NOT IN (SELECT DISTINCT test.country FROM test WHERE test.id =3);

答案 2 :(得分:1)

我认为你的情况就像是,

Table Data

你需要得到像, Expected Result Data

然后脚本就像,

SELECT DISTINCT t1.country 
FROM test t1
WHERE NOT EXISTS (
  SELECT 1 
  FROM test t2 
  WHERE t1.country = t2.country
  AND t2.id = 3
)

答案 3 :(得分:0)

SELECT DISTINCT c1.name 
FROM countries c1
WHERE NOT EXISTS (
  SELECT 1 
  FROM countries c2 
  WHERE c1.name = c2.name
  AND c2.id = 3
)