Loading

MySQL查询数据在一张表不在另一张表的记录

参考:https://www.cnblogs.com/jelly12345/p/16828722.html

方法一:使用 not in,易理解,效率低,仅适用单字段匹配
适用于数据量小的情况,子表数据少,查外表的时候走外表的索引,这种情况效率还行。
弊端:子查询里面不能有为null的字段,有的话查询结果会不准。
这种方式实际是和子表做HASH连接。

select *
from table1
where id not in (select id from table2);

方法二:使用 left join,条件给上where is null,适用多字段匹配
查询数据量为两表的笛卡尔积,返回左表的全部数据,左表数据量大的话,关联查询速度也会很慢

select t1.*
from table1 t1
         left join table2 t2 on t1.id = t2.id
where t2.id is null;

方法三:适用多字段匹配

select *
from table1
where (select count(1) as num from table2 where table2.ID = table1.ID) = 0;

方法四:适用多字段匹配
适用于子查询的表数据量少的情况,not exists使用的是子表的索引,但是外表数据量大的话,速度也会很慢。
本质是对外表做loop循环,每次loop循环再对内表进行查询。

select *
from table1
where not exists(select 1 from table2 where table1.ID = table2.ID);
posted @ 2022-12-29 11:56  溫柔の風  阅读(1683)  评论(0编辑  收藏  举报