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

Ram*_*sad 13 sql postgresql

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

select id from mytable where exclude(select id from another table)
Run Code Online (Sandbox Code Playgroud)

在第一个表中可用的id:

101,102,103,104,105

在第二个表中可用的id:

101,104

我想要结果:

102,103,105 (excluded values exist in second table)
Run Code Online (Sandbox Code Playgroud)

如何写查询?

小智 23

尝试

select id
from mytable
where id not in (select id from another_table);
Run Code Online (Sandbox Code Playgroud)

要么

select id
from mytable
except
select id
from another_table;
Run Code Online (Sandbox Code Playgroud)

  • 只是旁注:如果``'`在`another_table`中可以为null,则第一个查询将不起作用.在这种情况下,需要将`where not not null`添加到子选择中 (3认同)

Fra*_*ens 11

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

SELECT 
  id
FROM 
  mytable
    LEFT JOIN another_table ON mytable.id = another_table.id
WHERE
  another_table.id IS NULL;
Run Code Online (Sandbox Code Playgroud)