加入收藏 | 设为首页 | 会员中心 | 我要投稿 拼字网 - 核心网 (https://www.hexinwang.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MySql教程 > 正文

这些常被忽视的SQL错误用法,你知道吗

发布时间:2019-09-25 14:33:09 所属栏目:MySql教程 来源:佚名
导读:sql语句的执行顺序: FROM left_table ON join_condition join_type JOIN right_table WHERE where_condition GROUPBY group_by_list HAVING having_condition SELECT DISTINCT select_list ORDERBY order_by_condition LIMIT limit_number 1、LIMIT 语句

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

  1. SELECT target,  
  2.  Count(*)  
  3. FROM operation  
  4. WHERE target = 'rm-xxxx'  
  5. GROUP BY target 

执行计划变为:

  1. +----+-------------+-----------+------+---------------+-------+---------+-------+------+--------------------+ 
  2. | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | 
  3. +----+-------------+-----------+------+---------------+-------+---------+-------+------+--------------------+ 
  4. | 1 | SIMPLE | operation | ref | idx_4 | idx_4 | 514 | const | 1 | Using where; Using index | 
  5. +----+-------------+-----------+------+---------------+-------+---------+-------+------+--------------------+ 

关于 MySQL 外部条件不能下推的详细解释说明请参考以前文章:MySQL · 性能优化 · 条件下推到物化表 http://mysql.taobao.org/monthly/2016/07/08

7、提前缩小范围**

先上初始 SQL 语句:

  1. SELECT *  
  2. FROM my_order o  
  3.  LEFT JOIN my_userinfo u  
  4.  ON o.uid = u.uid 
  5.  LEFT JOIN my_productinfo p  
  6.  ON o.pid = p.pid  
  7. WHERE ( o.display = 0 )  
  8.  AND ( o.ostaus = 1 )  
  9. ORDER BY o.selltime DESC  
  10. LIMIT 0, 15  

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

  1. +----+-------------+-------+--------+---------------+---------+---------+-----------------+--------+----------------------------------------------------+ 
  2. | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | 
  3. +----+-------------+-------+--------+---------------+---------+---------+-----------------+--------+----------------------------------------------------+ 
  4. | 1 | SIMPLE | o | ALL | NULL | NULL | NULL | NULL | 909119 | Using where; Using temporary; Using filesort | 
  5. | 1 | SIMPLE | u | eq_ref | PRIMARY | PRIMARY | 4 | o.uid | 1 | NULL | 
  6. | 1 | SIMPLE | p | ALL | PRIMARY | NULL | NULL | NULL | 6 | Using where; Using join buffer (Block Nested Loop) | 
  7. +----+-------------+-------+--------+---------------+---------+---------+-----------------+--------+----------------------------------------------------+ 

(编辑:拼字网 - 核心网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!