我需要频繁地获取最近24小时的数据,并且这个查询经常运行。由于这会扫描许多行,因此频繁使用它会影响数据库性能。
MySql执行策略在created_at上选择索引,返回大约1,000,000行。这些行被逐个扫描以过滤customer_id = 10,我的最终结果是20000行。
如何优化此查询?
explain SELECT *
FROM `order`
WHERE customer_id = 10
and `created_at` >= NOW() - INTERVAL 1 DAY;
id : 1
select_type : SIMPLE
table : order
partitions : NULL
type : range
possible_keys : idx_customer_id, idx_order_created_at
key : idx_order_created_at
key_len : 5
ref : NULL
rows : 103357
filtered : 1.22
Extra : Using index condition; Using where发布于 2018-08-23 12:31:50
这种技术应该比所有其他答案都要好,尽管可能只有很小的差距:
而不是像这样索引orders:
PRIMARY KEY(order_id) -- AUTO_INCREMENT
INDEX(customer_id, ...) -- created_at, and possibly others执行此操作可将行“聚集”在一起:
PRIMARY KEY(customer_id, order_id)
INDEX (order_id) -- to keep AUTO_INCREMENT happy然后,您可以根据需要选择以customer_id开头的更多索引。或者不是。
另一个问题--您将如何处理20K行?对于客户来说,这是一个很大的问题,尤其是人类类型的客户。如果你继续使用它,难道你不能做一个更复杂的查询,做更多的工作,返回更少的行吗?这可能会更快。
https://stackoverflow.com/questions/51685834
复制相似问题