Home > Database > Mysql Tutorial > MYSQL IN 与 EXISTS 的优化示例介绍_MySQL

MYSQL IN 与 EXISTS 的优化示例介绍_MySQL

WBOY
Release: 2016-06-01 13:05:22
Original
982 people have browsed it

优化原则:小表驱动大表,即小的数据集驱动大的数据集。

############# 原理 (RBO) #####################

select * from A where id in (select id from B)
等价于:
for select id from B
for select * from A where A.id = B.id
Copy after login

当B表的数据集必须小于A表的数据集时,用in优于exists。

select * from A where exists (select 1 from B where B.id = A.id)
等价于
for select * from A
for select * from B where B.id = A.id
Copy after login

当A表的数据集系小于B表的数据集时,用exists优于in。

注意:A表与B表的ID字段应建立索引。

例如:

/** 执行时间:0.313s **/
SELECT SQL_NO_CACHE * FROM rocky_member m WHERE EXISTS (SELECT 1 FROM rocky_vip_appro a WHERE m.ID = a.user_id AND a.passed = 1);
/** 执行时间:0.160s **/
SELECT SQL_NO_CACHE * FROM rocky_member m WHERE m.ID in(SELECT ID FROM rocky_vip_appro WHERE passed = 1);
Copy after login

not in 和not exists用法类似。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template