我有两个桌子
myexercise
id | ex_name | ex_id | owner_id
1 exercise1 2 1
2 exercise2 3 1
和
exercise
id | ex_name
2 exercise1
3 exercise2
4 exercise3
我想编写SQL查询,该查询仅返回EXERCISE TABLE中的行,其中id不作为ex_id出现在MYEXERCISE表中。因此,它应该仅返回id => 4和ex_name => exercise3。 我认为可以使用JOINS来完成,但是我不知道如何。
答案 0 :(得分:1)
您可以使用where not exists
select t1.*
from Exercise t1
where not exists (select 1 from MyExercise t2 where t1.ex_id = t2.id)
或者是join
select t1.*
from Exercise t1
left join MyExercise t2
on t1.ex_id = t2.id
where t2.id is null
答案 1 :(得分:1)
您可以按以下方式尝试LEFT JOIN
:
Select *
from EXERCISE e left join MYEXERCISE me
ON e.id = ME.id
Where me.id IS NULL;
答案 2 :(得分:1)
select * from Exercise
where id not in (select ex_id from myExercise);
select * from Exercise t1
where not exists (select * from myExercise t2 where t1.Id = t2.ex_id);
select * from Exercise t1
left join MyExercise t2 on t1.Id = t2.ex_id
where myExercise.ex_id is null;
所有这3个查询都会做到这一点。