记踩到 MySQL in 子查询的“坑”

Crq
Crq
管理员
1871
文章
0
粉丝
Linux教程评论58字数 461阅读1分32秒阅读模式
前言

MySQL是项目中常用的数据库,其中in查询也是很常用。最近项目调试过程中,遇到一个出乎意料的select查询,竟然用了33秒!

一、表结构

1. userinfo 表

记踩到 MySQL in 子查询的“坑”-图片1

2. article 表

记踩到 MySQL in 子查询的“坑”-图片2

select*fromuserinfowhereidin(selectauthor_idfromartilcewheretype=1);

大家第一眼看到上面的SQL时,可能都会觉得这是一个很简单的子查询。先把author_id查出来,再用in查询一下。

如果有相关索引会非常快的,拆解来讲就是以下这样的:

1.selectauthor_idfromartilcewheretype=1;  2.select*fromuserinfowhereidin(1,2,3);

但是事实是这样的:

mysql> select count(*) from userinfo;

记踩到 MySQL in 子查询的“坑”-图片3

mysql> select count(*) from article;

记踩到 MySQL in 子查询的“坑”-图片4

mysql> select id,username from userinfo where id in (select author_id from article where type = 1);

记踩到 MySQL in 子查询的“坑”-图片5

33 秒为什么会这么慢呢?

三、问题原因

官方文档解释:in 子句在查询的时候有时会被转换为 exists 的方式来执行,变成逐条记录进行遍历(版本 5.5 中存在,5.6 中已做优化)。

记踩到 MySQL in 子查询的“坑”-图片6

参考:

https://dev.mysql.com/doc/refman/5.5/en/subquery-optimization.html

四、解决方式(版本5.5)

1. 使用临时表

select id,username from userinfo
where id in (select author_id from
(select author_id from article where type = 1) as tb);

记踩到 MySQL in 子查询的“坑”-图片7

2. 使用 join

select a.id,a.username from userinfo a, article b
where a.id = b.author_id and b.type = 1;

记踩到 MySQL in 子查询的“坑”-图片8

五、补充

版本 5.6 已针对子查询做了优化,方式跟【四】中的临时表方式一样,参考官方文档:

If materialization is not used, the optimizer sometimes rewrites a noncorrelated subquery as a correlated subquery.

For example, the following IN subquery is noncorrelated  ( where_condition involves only columns from t2 and not t1 ):

select * from t1

where t1.a in (select t2.b from t2 where where_condition);

The optimizer might rewrite this as an EXISTS correlated subquery:

select * from t1

where exists (select t2.b from t2 where where_condition and t1.a=t2.b);

Subquery materialization using a temporary table avoids such rewrites and makes it possible to execute the subquery only once rather than once per row of the outer query.

https://dev.mysql.com/doc/refman/5.6/en/subquery-materialization.html

文章来自微信公众号:HULK一线技术杂谈

weinxin
我的微信
微信号已复制
我的微信
这是我的微信扫一扫
 
Crq
  • 本文由 Crq 发表于2024年10月18日 02:17:55
  • 转载请注明:https://www.cncrq.com/11238.html
【技术快报】9.12-9.18 Linux教程

【技术快报】9.12-9.18

本期《linux就该这么学》的技术周报中,将为您推出Nginx源码安装及调优配置、国内三大云数据库测试对比、12个Linux进程管理命令介绍、怎样在Ubuntu中修改默认程序、在a...
最牛X的GCC 内联汇编 Linux教程

最牛X的GCC 内联汇编

正如大家知道的,在C语言中插入汇编语言,其是Linux中使用的基本汇编程序语法。本文将讲解 GCC 提供的内联汇编特性的用途和用法。对于阅读这篇文章,这里只有两个前提要求,很明显,...
10款优秀Vim插件帮你打造完美IDE Linux教程

10款优秀Vim插件帮你打造完美IDE

如果你稍微写过一点代码,就能知道“集成开发环境”(IDE)是多么的便利。不管是Java、C还是Python,当IDE会帮你检查语法、后台编译,或者自动导入你需要的库时,写代码就变得...
匿名

发表评论

匿名网友
:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:
确定

拖动滑块以完成验证