mariadb 有没有一种方法可以加速SQL中的SUM()函数

nlejzf6q  于 5个月前  发布在  其他
关注(0)|答案(2)|浏览(51)

我想知道有没有办法加快查询速度,

SELECT
     SUM(quantity) as quantity
    ,productId
FROM krakoweats.orderproducts
GROUP BY productId
ORDER BY quantity DESC
LIMIT 3;

字符串
table是这样的

Columns:
orderId int(11) PK 
productId int(11) PK 
quantity int(11) 
unityPrice double 
createdAt datetime 
updatedAt datetime


我想获取前3名销售的产品。该表有大约11万条记录,运行时间约为9秒,是否有方法加快速度?我正在与mariadb合作。
编辑:
我有这样的索引

+---------------+------------+------------------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+
| Table         | Non_unique | Key_name                           | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Ignored |
+---------------+------------+------------------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+
| orderproducts |          0 | order_products_order_id_product_id |            1 | orderId     | A         |       55747 |     NULL | NULL   |      | BTREE      |         |               | NO      |
| orderproducts |          0 | order_products_order_id_product_id |            2 | productId   | A         |      579777 |     NULL | NULL   |      | BTREE      |         |               | NO      |
| orderproducts |          1 | order_products_product_id          |            1 | productId   | A         |       31254 |     NULL | NULL   |      | BTREE      |         |               | NO      |
+---------------+------------+------------------------------------+--------------+-------------+-----------+-------------+----------+--------+------+-------

lnxxn5zx

lnxxn5zx1#

INDEX(product_id, order_id)  -- in this order

字符串
运行EXPLAIN SELECT ...EXPLAIN FORMAT=JSON SELECT ...
我认为你的设置将做两种;和我的,只有一个。
没有办法避免全表扫描。但是,如果你有一个Summary Table,对这样的查询可能会运行得快得多。

6jygbczu

6jygbczu2#

尝试:#1为productId字段创建单独的索引。#2在MariaDB的配置文件中增加查询设置的缓存

相关问题