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

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

发布时间:2019-07-22 15:59 所属栏目:115 来源:佚名
导读:去掉 exists 更改为 join,能够避免嵌套子查询,将执行时间从1.93秒降低为1毫秒。 SELECT* FROMmy_neighborn INNERJOINmessage_infom ONn.id=m.neighbor_id ANDm.inuser='xxx' LEFTJOINmy_neighbor_applysra ONn.id

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

  1. SELECT *  
  2. FROM   my_neighbor n   
  3.        INNER JOIN message_info m   
  4.                ON n.id = m.neighbor_id   
  5.                   AND m.inuser = 'xxx'   
  6.        LEFT JOIN my_neighbor_apply sra   
  7.               ON n.id = sra.neighbor_id   
  8.                  AND sra.user_id = 'xxx'   
  9. WHERE  n.topic_status < 4   
  10.        AND n.topic_type <> 5  

新的执行计划:

  1. +----+-------------+-------+--------+ -----+------------------------------------------+---------+ -----+------+ -----+  
  2. | id | select_type | table | type   | possible_keys     | key       | key_len | ref   | rows | Extra                 |  
  3. +----+-------------+-------+--------+ -----+------------------------------------------+---------+ -----+------+ -----+  
  4. |  1 | SIMPLE      | m     | ref    | | idx_message_info   | 122     | const    |    1 | Using index condition |  
  5. |  1 | SIMPLE      | n     | eq_ref | | PRIMARY   | 122     | ighbor_id |    1 | Using where      |  
  6. |  1 | SIMPLE      | sra   | ref    | | idx_user_id | 123     | const     |    1 | Using where           |  
  7. +----+-------------+-------+--------+ -----+------------------------------------------+---------+ -----+------+ -----+ 

6、条件下推

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

  •  聚合子查询;
  •  含有 LIMIT 的子查询;
  •  UNION 或 UNION ALL 子查询;
  •  输出字段中的子查询;

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

  1. SELECT *   
  2. FROM   (SELECT target,   
  3.                Count(*)   
  4.         FROM   operation   
  5.         GROUP  BY target) t   
  6. WHERE  target = 'rm-xxxx'   
  1. +----+-------------+------------+-------+---------------+-------------+---------+-------+------+-------------+  
  2. | id | select_type | table      | type  | possible_keys | key         | key_len | ref   | rows | Extra       |  
  3. +----+-------------+------------+-------+---------------+-------------+---------+-------+------+-------------+  
  4. |  1 | PRIMARY     | <derived2> | ref   | <auto_key0>   | <auto_key0> | 514     | const |    2 | Using where |  
  5. |  2 | DERIVED     | operation  | index | idx_4         | idx_4       | 519     | NULL  |   20 | Using index |  
  6. +----+-------------+------------+-------+---------------+-------------+---------+-------+------+-------------+ 

(编辑:ASP站长网)

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