码迷,mamicode.com
首页 > 数据库 > 详细

最快得到MYSQL两个表的差集

时间:2015-04-18 16:04:30      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

Mysql里不外乎就是 子查询 和 连接 两种方式.

设第一个表为table1, 第二个为table2, table1包含table2.

sql为:

 
 1 //子查询
 2 select table1.id from table1 
 3   where not exists 
 4     (select 1 from table2 
 5      where table1.id = table2.id
 6     );
 7  
 8 //外连接
 9 select table1.id from table1 
10   left join table2
11   on table1.id=table2.id
12 where table2.id is null;

 

高性能mysql里有类似的例子, 见 "When a correlated subquery is good" 一节. 它给出的数据, 外连接要快.

还有就是, 要最快, 那么最好只对 两张表的主键 做差集, 这样只过覆盖索引, 会快一些.

最快得到MYSQL两个表的差集

标签:

原文地址:http://www.cnblogs.com/wjgaas/p/4437453.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!