我正在尝试优化慢查询,在我的计算机上运行大约需要 5 分钟,在我的服务器上运行大约需要相同的时间(有 8gb 的内存)
SELECT
buyer_id as bid,
date_sold as dsold,
(
SELECT seller_id
FROM sale
WHERE buyer_id = bid
ORDER BY date_acquired
LIMIT 1
) as sid
from sale
WHERE seller_id = 3585328;
我为此查询创建了一个测试索引。
| sale | 1 | test | 1 | buyer_id | A | 4900222 | NULL | NULL | | BTREE | |
| sale | 1 | test | 2 | date_acquired | A | 14700667 | NULL | NULL | | BTREE | |
当我进行解释时,我得到
mysql> EXPLAIN SELECT buyer_id as bid,date_sold as dsold, (SELECT seller_id FROM sale WHERE buyer_id = bid ORDER BY date_acquired LIMIT 1) as sid from sale WHERE seller_id = 3585328;
+----+--------------------+-------+------+---------------+------+---------+-------+-------+------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------------+-------+------+---------------+------+---------+-------+-------+------------------------------------------+
| 1 | PRIMARY | sale | ref | test | test | 8 | const | 12466 | Using index |
| 2 | DEPENDENT SUBQUERY | sale | ref | test | test | 8 | func | 3 | Using where; Using index; Using filesort |
我知道子查询可能会很慢,但是我对如何优化没有任何想法。我不确定它是否重要,但如果我按buyer_id 分组,查询运行速度明显更快。用连接替换感觉很棘手,因为我在子查询中依赖“限制 1”。