MySQLはin/not inのsql文の代わりに


1.inとexists
inは外見と内表をhash接続し,existsは外表をloopループし,loopループのたびに内表をクエリーするが,existsはinより効率が高いという説は不正確であると考えられてきた.クエリの2つのテーブルのサイズが同じである場合、inとexistsの差は大きくありません.2つのテーブルのうち1つが小さい場合、1つが大きい場合は、サブクエリテーブルが大きい場合はexists、サブクエリテーブルが小さい場合はinを使用します.
一般的に、プライマリ・テーブルのデータは少なく、セカンダリ・テーブルのデータは多くなります.
例:table a(小表)、table b(大表)
select * from a where id in(select in from b)  -->   ,   a  id    ; 
select * from a where exists(select id from b where id=a.id)  -->   ,   b  id    。

これに対して、
select * from b where id in(select id from a)  -->   ,   b  id    

select * from b where exists(select id from a where id=b.id)  -->   ,   a  id    。

(1)性能の考慮は、この場合、サブテーブルが大きいメインテーブルが小さいexist、サブテーブルが小さいメインテーブルが大きいinの原則に従えばよい.
(2)書き方の違い、existのwhere条件は「…where exist(…where a.id=b.id)」
inのwhere条件は「......where id in(select id from......)」
2.not inとnot exists
クエリーを行うときに、連絡のある2つのテーブルをクエリーしたい場合、結果が1つのテーブルにあり、別のテーブルにないデータを取得したい場合は、not inを使用します.
select * from a where a.id not in (select id from b)

通常、not inを習慣的に使用し、データが少ない場合は可能ですが、データ量が大きくなるとnot inの効率が悪くなります.
なぜなら、not inとnot existsは、クエリ文がnot inを使用している場合、内外のテーブルがインデックスを使用せずに全テーブルスキャンされるからです.not extstsのサブクエリは、テーブルのインデックスにも使用できます.
だからその時計が大きくてもnot existsを使うのはnot inより速いです.
代わりにnot existsまたは外部接続を使用することをお勧めします.
select * from a where not exists(select id from b where id=a.id)

または
 
  
select * from  a left join  b on a.id = b.id where b.id is null;