设为首页 - 加入收藏 ASP站长网(Aspzz.Cn)- 科技、建站、经验、云计算、5G、大数据,站长网!
热搜: 创业者 数据 手机
当前位置: 首页 > 站长学院 > MySql教程 > 正文

8种你可能正在写错的SQL用法(3)

发布时间:2019-07-22 15:59 所属栏目:115 来源:佚名
导读:执行计划简化为: +----+-------------+-------+------+---------------+-------+---------+-------+------+-----------------------------------------------------+ |id|select_type|table|type|possible_keys|ke

执行计划简化为:

  1. +----+-------------+-------+------+---------------+-------+---------+-------+------+-----------------------------------------------------+  
  2. | id | select_type | table | type | possible_keys | key   | key_len | ref   | rows | Extra                                               |  
  3. +----+-------------+-------+------+---------------+-------+---------+-------+------+-----------------------------------------------------+  
  4. | 1  | PRIMARY     |       |      |               |       |         |       |      | Impossible WHERE noticed after reading const tables |  
  5. | 2  | DERIVED     | o     | ref  | idx_2,idx_5   | idx_5 | 8       | const | 1    | Using where; Using filesort                         |  
  6. +----+-------------+-------+------+---------------+-------+---------+-------+------+-----------------------------------------------------+ 

4、混合排序

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

  1. SELECT *   
  2. FROM   my_order o   
  3.        INNER JOIN my_appraise a ON a.orderid = o.id   
  4. ORDER  BY a.is_reply ASC,   
  5.           a.appraise_time DESC   
  6. LIMIT  0, 20  

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

  1. +----+-------------+-------+--------+-------------+---------+---------+---------------+---------+-+  
  2. | id | select_type | table | type   | possible_keys     | key     | key_len | ref      | rows    | Extra   
  3. +----+-------------+-------+--------+-------------+---------+---------+---------------+---------+-+  
  4. |  1 | SIMPLE      | a     | ALL    | idx_orderid | NULL    | NULL    | NULL    | 1967647 | Using filesort |  
  5. |  1 | SIMPLE      | o     | eq_ref | PRIMARY     | PRIMARY | 122     | a.orderid |       1 | NULL           |  
  6. +----+-------------+-------+--------+---------+---------+---------+-----------------+---------+-+ 

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

  1. SELECT *   
  2. FROM   ((SELECT *  
  3.          FROM   my_order o   
  4.                 INNER JOIN my_appraise a   
  5.                         ON a.orderid = o.id   
  6.                            AND is_reply = 0   
  7.          ORDER  BY appraise_time DESC   
  8.          LIMIT  0, 20)   
  9.         UNION ALL   
  10.         (SELECT *  
  11.          FROM   my_order o   
  12.                 INNER JOIN my_appraise a   
  13.                         ON a.orderid = o.id   
  14.                            AND is_reply = 1   
  15.          ORDER  BY appraise_time DESC   
  16.          LIMIT  0, 20)) t   
  17. ORDER  BY  is_reply ASC,   
  18.           appraisetime DESC   
  19. LIMIT  20; 

5、EXISTS语句

(编辑:ASP站长网)

网友评论
推荐文章
    热点阅读