有三种方法
1、用左连接,取连接后b的id为null
select *
from A left join B on A.id = b.id
where B.id is null
;
2、 (NOT)EXIST
select *
from A
where not exists (select * from B where A.id = B.id)
;
3、 (NOT) IN
select *
from A
where A.id not in (select id from B)
题目:数据库表如下,例如id=x,plant=5,那么后面plant=4的数据在查询时并不查询,只选择plant=5的数据,如果x中plant没有等于5的数据,那么plant=4的数据要全部查询,同理y也是这样,有5的就选择5,4不做查询,没有5就查询4.
题解:
1、将这个表划分成plant=5和plant=4两个表
SELECT *from test where plant=5
SELECT *from test where plant=4
2、将上面两个表进行合并,如果两张表的id相等意味着plant=5已经存在,那么后面的表的数据就是不需要查询的数据,现在将不需要查询的数据获取到,不理解的话可以从where那里去掉看一下合并的表,在理解一下
SELECT b.* from (SELECT *from test where plant=5) a ,(SELECT *from test where plant=4) b WHERE a.id=b.id GROUP BY id,plant,address
3、到这里就是这个文章标题的问题了,取A表有的B表没有的,上述面写的sql语句代表就是b表,这里选择前面讲的方式二进行解题
select *
from test a
where not exists (select * from (SELECT b.* from (SELECT *from test where plant=5) a ,(SELECT *from test where plant=4) b WHERE a.id=b.id GROUP BY id,plant,address) B where A.id = B.id and A.plant=B.plant AND A.address =B.address )