2012-01-07 93 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; 
相關問題