0

I have the following query where

  • A has 1 000 000 rows
  • B, C, D has 150 000 rows each
  • E has 50 000 rows

The query itself seems to take around 50 seconds to complete. It will usually contain a WHERE clause as it is doing a search through all the possible data in the database. Is there any way this could be improved?

SELECT A.one, A.two, A.three
FROM A
LEFT JOIN B ON ( A.id = B.id ) 
LEFT JOIN C ON ( A.id = C.d ) 
LEFT JOIN D ON ( A.id = D.id ) 
LEFT JOIN E ON ( A.name =  E.name 
AND  E.date <= A.date ) 
ORDER BY A.id ASC

Explain query:

+----+-------------+-------+--------+---------------+----------+---------+-----------+--------+-------------+
| id | select_type | table | type   | possible_keys | key      | key_len | ref       | rows   | Extra       |
+----+-------------+-------+--------+---------------+----------+---------+-----------+--------+-------------+
|  1 | SIMPLE      | A     | index  | NULL          | PRIMARY  | 17      | NULL      | 357752 |             |
|  1 | SIMPLE      | B     | eq_ref | PRIMARY       | PRIMARY  | 17      | db.A.id   |      1 | Using index |
|  1 | SIMPLE      | C     | eq_ref | PRIMARY       | PRIMARY  | 17      | db.A.id   |      1 | Using index |
|  1 | SIMPLE      | D     | eq_ref | PRIMARY       | PRIMARY  | 17      | db.A.id   |      1 | Using index |
|  1 | SIMPLE      | E     | ref    | Name,Date     | Name     | 62      | db.A.name |      1 |             |
+----+-------------+-------+--------+---------------+----------+---------+-----------+--------+-------------+
4

1 回答 1

1

我建议替换您拥有的索引E-NameDate在两者上都使用双列索引,因为对于最后一个连接,您实际上是从E哪里选择namedate匹配一个标准。因为name是eq,所以应该在索引中排在第一位。

ALTER TABLE `E` ADD INDEX idx_join_optimise (`name`,`date`)

这将使连接选择完全使用索引。

另外 - 我假设这是一个示例查询,但您似乎没有使用BC或者D可能会减慢它的速度。

如果WHERE您提到的子句使用其他表中的值,我建议INNER JOIN根据标准将它们更改为 .. (如果您发布一些您正在做的事情的示例会有所帮助)

于 2013-10-25T00:50:57.627 回答