2012-01-07 77 views
8

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

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

第一表格可ID:

101,102,103,104,105

在第二个表提供ID:

101,104

我想结果是:

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

如何为此写入查询?

回答

16

尝试

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

select id 
from mytable 
except 
select id 
from another_table; 
+2

只是一个侧面说明:如果'ìd'可以为null在'another_table'中,第一个查询不起作用。在这种情况下,'where id不为空'需要被添加到子选择中 – 2012-01-07 08:55:30

8

使用LEFT JOIN的IS NULL也是一种选择:

SELECT 
    id 
FROM 
    mytable 
    LEFT JOIN another_table ON mytable.id = another_table.id 
WHERE 
    another_table.id IS NULL; 
相关问题