虽然它们是相同的,但是SQL查询性能会有所不同

时间:2018-06-13 14:14:28

标签: mysql sql

有两个表及其结构如下:

mysql> desc product;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | NO   | PRI | NULL    |       |
| brand | varchar(20) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.02 sec)


mysql> desc sales;
+-------------+-------------+------+-----+---------+-------+
| Field       | Type        | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| id          | int(11)     | YES  |     | NULL    |       |
| yearofsales | varchar(10) | YES  |     | NULL    |       |
| price       | int(11)     | YES  |     | NULL    |       |
+-------------+-------------+------+-----+---------+-------+
3 rows in set (0.01 sec)

此处id是外键。

查询如下:

1

mysql> select brand,sum(price),yearofsales 
       from product p, sales s 
       where p.id=s.id 
       group by s.id,yearofsales;
+-------+------------+-------------+
| brand | sum(price) | yearofsales |
+-------+------------+-------------+
| Nike  |  917504000 | 2012        |
| FF    |  328990720 | 2010        |
| FF    |  328990720 | 2011        |
| FF    |  723517440 | 2012        |
+-------+------------+-------------+
4 rows in set (1.91 sec)

2

mysql> select brand,tmp.yearofsales,tmp.sum 
       from product p 
       join (
           select id,yearofsales,sum(price) as sum
           from sales
           group by yearofsales,id
       ) tmp on p.id=tmp.id ;
+-------+-------------+-----------+
| brand | yearofsales | sum       |
+-------+-------------+-----------+
| Nike  | 2012        | 917504000 |
| FF    | 2011        | 328990720 |
| FF    | 2012        | 723517440 |
| FF    | 2010        | 328990720 |
+-------+-------------+-----------+
4 rows in set (1.59 sec)

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

1 个答案:

答案 0 :(得分:1)

您可以检查两个查询的执行计划以及两个表上的索引,以查看一个查询占用多少查询的原因。此外,您无法运行一个简单的测试并信任结果,有许多因素会影响查询的执行,例如服务器在执行一个查询时忙于其他事情,因此运行速度较慢。您必须多次运行这两个查询,然后比较平均值。

但是,强烈建议使用显式连接而不是隐式连接:

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