欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MySQL常见的8种SQL错误用法

程序员文章站 2023-10-31 17:58:04
MySQL常见的8种SQL错误用法 前言 MySQL在2016年仍然保持强劲的数据库流行度增长趋势。越来越多的客户将自己的应用建立在MySQL数据库之上,甚至是从Oracle迁移到MySQL上来。但也存在部分客户在使用MySQL数据库的过程中遇到一些比如响应时间慢,CPU打满等情况。 阿里云RDS专 ......

mysql常见的8种sql错误用法

前言

mysql在2016年仍然保持强劲的数据库流行度增长趋势。越来越多的客户将自己的应用建立在mysql数据库之上,甚至是从oracle迁移到mysql上来。但也存在部分客户在使用mysql数据库的过程中遇到一些比如响应时间慢,cpu打满等情况。

阿里云rds专家服务团队帮助云上客户解决过很多紧急问题。现将《apsaradb专家诊断报告》中出现的部分常见sql问题总结如下,供大家参考。

1、limit 语句

分页查询是最常用的场景之一,但也通常也是最容易出问题的地方。

比如对于下面简单的语句,一般 dba 想到的办法是在 type, name, create_time 字段上加组合索引。这样条件排序都能有效的利用到索引,性能迅速提升。

 

 

 

select * 
from   operation 
where  type = 'sqlstats' 
       and name = 'slowlog' 
order  by create_time 
limit  1000, 10;复制代码

 

好吧,可能90%以上的 dba 解决该问题就到此为止。

但当 limit 子句变成 “limit 1000000,10” 时,程序员仍然会抱怨:我只取10条记录为什么还是慢?

要知道数据库也并不知道第1000000条记录从什么地方开始,即使有索引也需要从头计算一次。出现这种性能问题,多数情形下是程序员偷懒了。

在前端数据浏览翻页,或者大数据分批导出等场景下,是可以将上一页的最大值当成参数作为查询条件的。sql 重新设计如下:

 

 

 

select   * 
from     operation 
where    type = 'sqlstats' 
and      name = 'slowlog' 
and      create_time > '2017-03-16 14:00:00' 
order by create_time limit 10;复制代码

 

在新设计下查询时间基本固定,不会随着数据量的增长而发生变化。

2、隐式转换

sql语句中查询变量和字段定义类型不匹配是另一个常见的错误。比如下面的语句:

 

 

 

mysql> explain extended select * 
     > from   my_balance b 
     > where  b.bpn = 14000000123 
     >       and b.isverified is null ;
mysql> show warnings;
| warning | 1739 | cannot use ref access on index 'bpn' due to type or collation conversion on field 'bpn'复制代码

 

其中字段 bpn 的定义为 varchar(20),mysql 的策略是将字符串转换为数字之后再比较。函数作用于表字段,索引失效。

上述情况可能是应用程序框架自动填入的参数,而不是程序员的原意。现在应用框架很多很繁杂,使用方便的同时也小心它可能给自己挖坑。

3、关联更新、删除

虽然 mysql5.6 引入了物化特性,但需要特别注意它目前仅仅针对查询语句的优化。对于更新或删除需要手工重写成 join。

比如下面 update 语句,mysql 实际执行的是循环/嵌套子查询(dependent subquery),其执行时间可想而知。

 

 

 

update operation o 
set    status = 'applying' 
where  o.id in (select id 
                from   (select o.id, 
                               o.status 
                        from   operation o 
                        where  o.group = 123 
                               and o.status not in ( 'done' ) 
                        order  by o.parent, 
                                  o.id 
                        limit  1) t);复制代码

 

执行计划:

 

 

 

+----+--------------------+-------+-------+---------------+---------+---------+-------+------+-----------------------------------------------------+
| id | select_type        | table | type  | possible_keys | key     | key_len | ref   | rows | extra                                               |
+----+--------------------+-------+-------+---------------+---------+---------+-------+------+-----------------------------------------------------+
| 1  | primary            | o     | index |               | primary | 8       |       | 24   | using where; using temporary                        |
| 2  | dependent subquery |       |       |               |         |         |       |      | impossible where noticed after reading const tables |
| 3  | derived            | o     | ref   | idx_2,idx_5   | idx_5   | 8       | const | 1    | using where; using filesort                         |
+----+--------------------+-------+-------+---------------+---------+---------+-------+------+-----------------------------------------------------+复制代码

 

重写为 join 之后,子查询的选择模式从 dependent subquery 变成 derived,执行速度大大加快,从7秒降低到2毫秒。

 

 

 

update operation o 
       join  (select o.id, 
                            o.status 
                     from   operation o 
                     where  o.group = 123 
                            and o.status not in ( 'done' ) 
                     order  by o.parent, 
                               o.id 
                     limit  1) t
         on o.id = t.id 
set    status = 'applying' 复制代码

 

执行计划简化为:

 

 

 

+----+-------------+-------+------+---------------+-------+---------+-------+------+-----------------------------------------------------+
| id | select_type | table | type | possible_keys | key   | key_len | ref   | rows | extra                                               |
+----+-------------+-------+------+---------------+-------+---------+-------+------+-----------------------------------------------------+
| 1  | primary     |       |      |               |       |         |       |      | impossible where noticed after reading const tables |
| 2  | derived     | o     | ref  | idx_2,idx_5   | idx_5 | 8       | const | 1    | using where; using filesort                         |
+----+-------------+-------+------+---------------+-------+---------+-------+------+-----------------------------------------------------+复制代码

 

4、混合排序

mysql 不能利用索引进行混合排序。但在某些场景,还是有机会使用特殊方法提升性能的。

 

 

 

select * 
from   my_order o 
       inner join my_appraise a on a.orderid = o.id 
order  by a.is_reply asc, 
          a.appraise_time desc 
limit  0, 20 复制代码

 

执行计划显示为全表扫描:

 

 

 

+----+-------------+-------+--------+-------------+---------+---------+---------------+---------+-+
| id | select_type | table | type   | possible_keys     | key     | key_len | ref      | rows    | extra    
+----+-------------+-------+--------+-------------+---------+---------+---------------+---------+-+
|  1 | simple      | a     | all    | idx_orderid | null    | null    | null    | 1967647 | using filesort |
|  1 | simple      | o     | eq_ref | primary     | primary | 122     | a.orderid |       1 | null           |
+----+-------------+-------+--------+---------+---------+---------+-----------------+---------+-+复制代码

 

由于 is_reply 只有0和1两种状态,我们按照下面的方法重写后,执行时间从1.58秒降低到2毫秒。

 

 

 

select * 
from   ((select *
         from   my_order o 
                inner join my_appraise a 
                        on a.orderid = o.id 
                           and is_reply = 0 
         order  by appraise_time desc 
         limit  0, 20) 
        union all 
        (select *
         from   my_order o 
                inner join my_appraise a 
                        on a.orderid = o.id 
                           and is_reply = 1 
         order  by appraise_time desc 
         limit  0, 20)) t 
order  by  is_reply asc, 
          appraisetime desc 
limit  20;复制代码

 

5、exists语句

mysql 对待 exists 子句时,仍然采用嵌套子查询的执行方式。如下面的 sql 语句:

 

 

 

select *
from   my_neighbor n 
       left join my_neighbor_apply sra 
              on n.id = sra.neighbor_id 
                 and sra.user_id = 'xxx' 
where  n.topic_status < 4 
       and exists(select 1 
                  from   message_info m 
                  where  n.id = m.neighbor_id 
                         and m.inuser = 'xxx') 
       and n.topic_type <> 5 复制代码

 

执行计划为:

 

 

 

+----+--------------------+-------+------+-----+------------------------------------------+---------+-------+---------+ -----+
| id | select_type        | table | type | possible_keys     | key   | key_len | ref   | rows    | extra   |
+----+--------------------+-------+------+ -----+------------------------------------------+---------+-------+---------+ -----+
|  1 | primary            | n     | all  |  | null     | null    | null  | 1086041 | using where                   |
|  1 | primary            | sra   | ref  |  | idx_user_id | 123     | const |       1 | using where          |
|  2 | dependent subquery | m     | ref  |  | idx_message_info   | 122     | const |       1 | using index condition; using where |
+----+--------------------+-------+------+ -----+------------------------------------------+---------+-------+---------+ -----+复制代码

 

去掉 exists 更改为 join,能够避免嵌套子查询,将执行时间从1.93秒降低为1毫秒。

 

 

 

select *
from   my_neighbor n 
       inner join message_info m 
               on n.id = m.neighbor_id 
                  and m.inuser = 'xxx' 
       left join my_neighbor_apply sra 
              on n.id = sra.neighbor_id 
                 and sra.user_id = 'xxx' 
where  n.topic_status < 4 
       and n.topic_type <> 5 复制代码

 

新的执行计划:

 

 

 

+----+-------------+-------+--------+ -----+------------------------------------------+---------+ -----+------+ -----+
| id | select_type | table | type   | possible_keys     | key       | key_len | ref   | rows | extra                 |
+----+-------------+-------+--------+ -----+------------------------------------------+---------+ -----+------+ -----+
|  1 | simple      | m     | ref    | | idx_message_info   | 122     | const    |    1 | using index condition |
|  1 | simple      | n     | eq_ref | | primary   | 122     | ighbor_id |    1 | using where      |
|  1 | simple      | sra   | ref    | | idx_user_id | 123     | const     |    1 | using where           |
+----+-------------+-------+--------+ -----+------------------------------------------+---------+ -----+------+ -----+复制代码

 

6、条件下推

外部查询条件不能够下推到复杂的视图或子查询的情况有:

  • 聚合子查询;

  • 含有 limit 的子查询;

  • union 或 union all 子查询;

  • 输出字段中的子查询;

如下面的语句,从执行计划可以看出其条件作用于聚合子查询之后:

 

 

 

select * 
from   (select target, 
               count(*) 
        from   operation 
        group  by target) t 
where  target = 'rm-xxxx'复制代码

 

 

 

+----+-------------+------------+-------+---------------+-------------+---------+-------+------+-------------+
| id | select_type | table      | type  | possible_keys | key         | key_len | ref   | rows | extra       |
+----+-------------+------------+-------+---------------+-------------+---------+-------+------+-------------+
|
1
| primary     |
 <derived2> 
| ref   |
 <auto_key
0
>   
| <auto_key0> |
514
| const |
2
| using where |
|  2 | derived     | operation  | index | idx_4         | idx_4       | 519     | null  |   20 | using index |
+----+-------------+------------+-------+---------------+-------------+---------+-------+------+-------------+复制代码

 

确定从语义上查询条件可以直接下推后,重写如下:

 

 

 

select target, 
       count(*) 
from   operation 
where  target = 'rm-xxxx' 
group  by target复制代码

 

执行计划变为:

 

 

 

+----+-------------+-----------+------+---------------+-------+---------+-------+------+--------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | extra |
+----+-------------+-----------+------+---------------+-------+---------+-------+------+--------------------+
| 1 | simple | operation | ref | idx_4 | idx_4 | 514 | const | 1 | using where; using index |
+----+-------------+-----------+------+---------------+-------+---------+-------+------+--------------------+复制代码

 

关于 mysql 外部条件不能下推的详细解释说明请参考文章:

http://mysql.taobao.org/monthly/2016/07/08

7、提前缩小范围

先上初始 sql 语句:

 

 

 

select * 
from   my_order o 
       left join my_userinfo u 
              on o.uid = u.uid
       left join my_productinfo p 
              on o.pid = p.pid 
where  ( o.display = 0 ) 
       and ( o.ostaus = 1 ) 
order  by o.selltime desc 
limit  0, 15 复制代码

 

该sql语句原意是:先做一系列的左连接,然后排序取前15条记录。从执行计划也可以看出,最后一步估算排序记录数为90万,时间消耗为12秒。

 

 

 

+----+-------------+-------+--------+---------------+---------+---------+-----------------+--------+----------------------------------------------------+
| id | select_type | table | type   | possible_keys | key     | key_len | ref             | rows   | extra                                              |
+----+-------------+-------+--------+---------------+---------+---------+-----------------+--------+----------------------------------------------------+
|  1 | simple      | o     | all    | null          | null    | null    | null            | 909119 | using where; using temporary; using filesort       |
|  1 | simple      | u     | eq_ref | primary       | primary | 4       | o.uid |      1 | null                                               |
|  1 | simple      | p     | all    | primary       | null    | null    | null            |      6 | using where; using join buffer (block nested loop) |
+----+-------------+-------+--------+---------------+---------+---------+-----------------+--------+----------------------------------------------------+复制代码

 

由于最后 where 条件以及排序均针对最左主表,因此可以先对 my_order 排序提前缩小数据量再做左连接。sql 重写后如下,执行时间缩小为1毫秒左右。

 

 

 

select * 
from (
select * 
from   my_order o 
where  ( o.display = 0 ) 
       and ( o.ostaus = 1 ) 
order  by o.selltime desc 
limit  0, 15
) o 
     left join my_userinfo u 
              on o.uid = u.uid 
     left join my_productinfo p 
              on o.pid = p.pid 
order by  o.selltime desc
limit 0, 15复制代码

 

再检查执行计划:子查询物化后(select_type=derived)参与 join。虽然估算行扫描仍然为90万,但是利用了索引以及 limit 子句后,实际执行时间变得很小。

 

 

 

+----+-------------+------------+--------+---------------+---------+---------+-------+--------+----------------------------------------------------+
| id | select_type | table      | type   | possible_keys | key     | key_len | ref   | rows   | extra                                              |
+----+-------------+------------+--------+---------------+---------+---------+-------+--------+----------------------------------------------------+
|  1 | primary     | <derived2> | all    | null          | null    | null    | null  |     15 | using temporary; using filesort                    |
|  1 | primary     | u          | eq_ref | primary       | primary | 4       | o.uid |      1 | null                                               |
|  1 | primary     | p          | all    | primary       | null    | null    | null  |      6 | using where; using join buffer (block nested loop) |
|  2 | derived     | o          | index  | null          | idx_1   | 5       | null  | 909112 | using where                                        |
+----+-------------+------------+--------+---------------+---------+---------+-------+--------+----------------------------------------------------+复制代码

 

8、中间结果集下推

再来看下面这个已经初步优化过的例子(左连接中的主表优先作用查询条件):

 

 

 

select    a.*, 
          c.allocated 
from      ( 
              select   resourceid 
              from     my_distribute d 
                   where    isdelete = 0 
                   and      cusmanagercode = '1234567' 
                   order by salecode limit 20) a 
left join 
          ( 
              select   resourcesid, sum(ifnull(allocation, 0) * 12345) allocated 
              from     my_resources 
                   group by resourcesid) c 
on        a.resourceid = c.resourcesid复制代码

 

那么该语句还存在其它问题吗?不难看出子查询 c 是全表聚合查询,在表数量特别大的情况下会导致整个语句的性能下降。

其实对于子查询 c,左连接最后结果集只关心能和主表 resourceid 能匹配的数据。因此我们可以重写语句如下,执行时间从原来的2秒下降到2毫秒。

 

 

 

select    a.*, 
          c.allocated 
from      ( 
                   select   resourceid 
                   from     my_distribute d 
                   where    isdelete = 0 
                   and      cusmanagercode = '1234567' 
                   order by salecode limit 20) a 
left join 
          ( 
                   select   resourcesid, sum(ifnull(allocation, 0) * 12345) allocated 
                   from     my_resources r, 
                            ( 
                                     select   resourceid 
                                     from     my_distribute d 
                                     where    isdelete = 0 
                                     and      cusmanagercode = '1234567' 
                                     order by salecode limit 20) a 
                   where    r.resourcesid = a.resourcesid 
                   group by resourcesid) c 
on        a.resourceid = c.resourcesid复制代码

 

但是子查询 a 在我们的sql语句中出现了多次。这种写法不仅存在额外的开销,还使得整个语句显的繁杂。使用 with 语句再次重写:

 

 

 

with a as 
( 
         select   resourceid 
         from     my_distribute d 
         where    isdelete = 0 
         and      cusmanagercode = '1234567' 
         order by salecode limit 20)
select    a.*, 
          c.allocated 
from      a 
left join 
          ( 
                   select   resourcesid, sum(ifnull(allocation, 0) * 12345) allocated 
                   from     my_resources r, 
                            a 
                   where    r.resourcesid = a.resourcesid 
                   group by resourcesid) c 
on        a.resourceid = c.resourcesid复制代码

 

总结

数据库编译器产生执行计划,决定着sql的实际执行方式。但是编译器只是尽力服务,所有数据库的编译器都不是尽善尽美的。

上述提到的多数场景,在其它数据库中也存在性能问题。了解数据库编译器的特性,才能避规其短处,写出高性能的sql语句。

程序员在设计数据模型以及编写sql语句时,要把算法的思想或意识带进来。

编写复杂sql语句要养成使用 with 语句的习惯。简洁且思路清晰的sql语句也能减小数据库的负担 。