2

我正在尝试优化慢查询,在我的计算机上运行大约需要 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”。

4

2 回答 2

0

首先,您的查询对我来说似乎很奇怪。除非我没有得到您想要做的事情,否则我不明白您为什么要执行此子查询,因为您想获得“buyer_id”但其中的buyer_id = 3585328;

其次,如果这是一个错字,并且您想做其他事情,如果您按 date_acquired 排序,则应该在 date_acquired 上有一个索引;

于 2013-02-18T10:25:32.700 回答
0

如果您在这里的目的是仅获取最新信息sid;尝试类似:

SELECT
    t1.buyer_id AS bid,
    t1.date_sold AS dsold,
    t1.id AS sid
FROM
    sale AS t1
LEFT OUTER JOIN
    sale AS t2
    ON (t1.buyer_id = t2.buyer_id AND t1.date_acquired < t2.date_acquired)
WHERE t2.date_acquired IS NULL;
于 2013-02-18T10:31:16.160 回答