我有一个正在执行的 MySQL 连接查询,但它永远不会完成:
SELECT t1.`id` FROM `person` as t1
JOIN `temp_table` as t2
on t1.`date` = t2.`date`
and t1.`name` = t2.`name`
and t1.`country_id`= t2.`country_id`
person 表和 temp_table 具有完全相同的列。
当我使用 explain 运行查询时,我看到以下结果:
1 SIMPLE t1 index test test 777 NULL 99560 Using where; Using index
1 SIMPLE t2 ref test test 777 development.t1.date,development.t1.name,development.t1.country_id 1 Using index
我使用以下语句为两个表创建了索引:
ALTER TABLE `person` ADD INDEX `test` (`date`,`name`,`country_id`)
ALTER TABLE `temp_table` ADD INDEX `test` (`date`,`name`,`country_id`)
每个表都有大约 100,000 行,因此连接应该返回 100,000 行。我假设这个查询很慢,因为在 t1 表上扫描的行数很大。如果我应用了索引,我不确定为什么会这样。任何帮助,将不胜感激。
最佳答案
连接是乘以元组的数量。尝试改用自然联接或分组。
SELECT t1.`id` FROM `person` as t1
NATURAL JOIN `temp_table` as t2
我不知道 mysql,但在 psql 中应该可以,应该是类似的。
关于MySQL 连接查询非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21807188/