我试图优化查询速度慢,大约需要5分钟,我的服务器在我的电脑上运行,大约相同的时间(即具有RAM的8GB)慢MySQL的子查询
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”,所以用连接代替感觉很棘手。
是那个date_acquired索引降序或升序? – iiro 2013-02-18 10:19:36
我可能在这里误解了一些东西,但是您的子查询不会只是每次都返回您的'WHERE'子句中指定的买家ID?在这种情况下,它有什么意义? – 2013-02-18 10:20:32
'slow mysql',是不是其中的那些单词冗余? – 2013-02-18 10:20:35