mysql - SQL 查询性能虽然相同但有所不同

标签 mysql sql

有2个表,它们的结构如下:

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)

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

最佳答案

您可以检查两个查询的执行计划和两个表上的索引,以了解为什么一个查询比另一个查询花费更多。此外,您不能运行一个简单的测试并相信结果,有很多因素会影响查询的执行,例如服务器在执行一个查询时正忙于其他事情,因此运行速度较慢。您必须多次运行这两个查询,然后比较平均值。

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

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

关于mysql - SQL 查询性能虽然相同但有所不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50839447/

相关文章:

Mysql按时间选择数据但不忽略值为0的时间

sql - 分区表查询仍在扫描所有分区

PHP Laravel : Access denied for user 'homestead' @'localhost' (using password: YES)

mysql - 查询未从数据库输出所有相关结果

php - API平台: Can't get using a json data type with MySQL to work

sql - 为什么我们总是喜欢在SQL语句中使用参数?

c# - 如何计算我的应用程序中的在线用户数?

mysql - 回滚多个查询

mysql - 如何按音叉分组?

sql - 如何使用这种不寻常的匹配条件编写连接?