带有关系表的条件SELECT SQL

时间:2016-11-12 15:43:27

标签: mysql sql

假设我在table1中有一个id,它是table2中的一个外键,table2中有一个名为condition的列。

我需要从表1中选择所有不在table2中且条件= 1的ID。

因此对于表1和#34中的id;选择它"如果它不在table2中,其中condition = 1。

编辑:我使用了Ahsan Habib的答案,效果很好!

3 个答案:

答案 0 :(得分:0)

这几乎是您要求的直接翻译:

select t1.*
from table1 t1
where t1.id not in (select t2.id from table2 t2 where t2.condition = 1);

答案 1 :(得分:0)

使用NOT EXISTS

的另一种方法
select t1.*
from table1 t1
where NOT EXISTS(select 1 from table2 t2 where t1.id = t2.id and t2.condition = 1);

答案 2 :(得分:0)

如果您只想从table1中选择ID列,这将正常工作....它只是一个简单的设置操作 select id from t1 minus select id from t2 where condition = 1;

对于您可能尝试的所有列

select * from t1 whare id not in (select id from t2 where condition = 1);

相关问题