从表中选择排除另一个表中的值的值

时间:2012-01-07 08:00:32

标签: sql postgresql

我正在使用PostgreSQL数据库。我希望通过排除另一个表中存在的值来从表中获取列值。

select id from mytable where exclude(select id from another table)

在First table available id:

101,102,103,104,105

在第二个表中可用id:

101104

我想要结果:

102,103,105 (excluded values exist in second table)

如何写查询?

3 个答案:

答案 0 :(得分:20)

尝试

select id
from mytable
where id not in (select id from another_table);

select id
from mytable
except
select id
from another_table;

答案 1 :(得分:10)

使用LEFT JOIN IS NULL也是一个选项:

SELECT 
  id
FROM 
  mytable
    LEFT JOIN another_table ON mytable.id = another_table.id
WHERE
  another_table.id IS NULL;

答案 2 :(得分:0)

我尝试了“ user554546”中的解决方案。不确定示例中发生了什么,但是我必须选择Distinct,因为一旦在another_table中有两个值,则我的表将显示两次未过滤的值。

所以可以说another_table有

|ID|
|03|
|04|
|06|

main_table拥有

|ID|
|01|
|02|
|03|
|04|
|05|
|06|

执行完查询后,main_table将显示以下

|ID|
|01|
|01|
|01|
|02|
|02|
|02|
|05|
|05|
|05|

似乎可以解决不同的问题,但是有什么主意为什么会这样?

相关问题