从表B中选择表A中具有条件的表A中选择

时间:2016-06-15 10:48:15

标签: mysql

我有tableA

id  | name      
--------------
1   | John
2   | Alice     
3   | Bob   

和表B

id  | tableA_id | setting 
--------------------------
1   | 1         |  1
2   | 2         |  0

我想在表A中选择表B中不存在的所有唯一ID,表B中的条件设置为0。

示例我想收到

id  | name      
--------------
1   | John    
3   | Bob   

我可以使用查询:

SELECT * FROM tableA WHERE id NOT IN (SELECT tableA_id from tableB WHERE setting = 0)

但我认为这是缓慢的,因为2个表很大。我认为这个查询会影响性能。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

试试这个;)

select t1.*
from tableA t1
left join tableB t2
on t1.id = t2.tableA_id
where t2.setting <> 0 or t2.id is null

DEMO HERE

或者这个:

select *
from tableA
where not exists (
    select 1 from tableB where tableA.id = tableB.tableA_id and tableB.setting = 0
)

DEMO HERE

相关问题