sql查询性能是不同的,尽管它们是相同的

wpx232ag  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(250)

共有两个表格,其结构如下:

  1. mysql> desc product;
  2. +-------+-------------+------+-----+---------+-------+
  3. | Field | Type | Null | Key | Default | Extra |
  4. +-------+-------------+------+-----+---------+-------+
  5. | id | int(11) | NO | PRI | NULL | |
  6. | brand | varchar(20) | YES | | NULL | |
  7. +-------+-------------+------+-----+---------+-------+
  8. 2 rows in set (0.02 sec)
  9. mysql> desc sales;
  10. +-------------+-------------+------+-----+---------+-------+
  11. | Field | Type | Null | Key | Default | Extra |
  12. +-------------+-------------+------+-----+---------+-------+
  13. | id | int(11) | YES | | NULL | |
  14. | yearofsales | varchar(10) | YES | | NULL | |
  15. | price | int(11) | YES | | NULL | |
  16. +-------------+-------------+------+-----+---------+-------+
  17. 3 rows in set (0.01 sec)

在这里 id 是外键。
查询内容如下:
1

  1. mysql> select brand,sum(price),yearofsales
  2. from product p, sales s
  3. where p.id=s.id
  4. group by s.id,yearofsales;
  5. +-------+------------+-------------+
  6. | brand | sum(price) | yearofsales |
  7. +-------+------------+-------------+
  8. | Nike | 917504000 | 2012 |
  9. | FF | 328990720 | 2010 |
  10. | FF | 328990720 | 2011 |
  11. | FF | 723517440 | 2012 |
  12. +-------+------------+-------------+
  13. 4 rows in set (1.91 sec)

2

  1. mysql> select brand,tmp.yearofsales,tmp.sum
  2. from product p
  3. join (
  4. select id,yearofsales,sum(price) as sum
  5. from sales
  6. group by yearofsales,id
  7. ) tmp on p.id=tmp.id ;
  8. +-------+-------------+-----------+
  9. | brand | yearofsales | sum |
  10. +-------+-------------+-----------+
  11. | Nike | 2012 | 917504000 |
  12. | FF | 2011 | 328990720 |
  13. | FF | 2012 | 723517440 |
  14. | FF | 2010 | 328990720 |
  15. +-------+-------------+-----------+
  16. 4 rows in set (1.59 sec)

问题是:为什么第二个查询比第一个查询花费更少的时间?我也以不同的顺序执行过多次。

k5ifujac

k5ifujac1#

您可以检查两个查询的执行计划以及两个表上的索引,以了解为什么一个查询比另一个查询占用更多的时间。另外,您不能运行一个简单的测试并信任结果,有许多因素会影响查询的执行,例如服务器在执行一个查询时忙于其他事情,因此它运行得比较慢。您必须运行两个查询很多次,然后比较平均值。
但是,强烈建议使用显式联接而不是隐式联接:

  1. SELECT brand, SUM(price), yearofsales
  2. FROM product p
  3. INNER JOIN sales s ON p.id = s.id
  4. GROUP BY s.id, yearofsales;

相关问题