gpt4 book ai didi

mysql - 简单JOIN时如何防止全表扫描?

转载 作者:可可西里 更新时间:2023-11-01 08:38:25 25 4
gpt4 key购买 nike

我有两个表,TableA 和 TableB:

CREATE TABLE `TableA` (
`shared_id` int(10) unsigned NOT NULL default '0',
`foo` int(10) unsigned NOT NULL,
PRIMARY KEY (`shared_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1


CREATE TABLE `TableB` (
`shared_id` int(10) unsigned NOT NULL auto_increment,
`bar` int(10) unsigned NOT NULL,
KEY `shared_id` (`shared_id`)
) ENGINE=MyISAM AUTO_INCREMENT=1001 DEFAULT CHARSET=latin1

这是我的查询:

SELECT TableB.bar 
FROM TableB, TableA
WHERE TableA.foo = 1000
AND TableA.shared_id = TableB.shared_id;

问题是:

mysql> explain SELECT TableB.bar FROM TableB, TableA WHERE TableA.foo = 1000 AND TableA.shared_id = TableB.shared_id;

+----+-------------+--------------+--------+---------------+---------+---------+------------------------------------------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+--------------+--------+---------------+---------+---------+------------------------------------------+------+-------------+
| 1 | SIMPLE | TableB | ALL | shared_id | NULL | NULL | NULL | 1000 | |
| 1 | SIMPLE | TableA | eq_ref | PRIMARY | PRIMARY | 4 | MyDatabase.TableB.shared_id | 1 | Using where |
+----+-------------+--------------+--------+---------------+---------+---------+------------------------------------------+------+-------------+

我可以添加一个索引来防止对 TableB 进行全表扫描吗?

最佳答案

Runcible,您的查询可以使用一些重写。您应该始终在 ON 子句中而不是在 WHERE 中指定 JOIN 条件。

您的查询将变为:

SELECT TableB.bar 
FROM TableB
JOIN TableA
ON TableB.shared_id = TableA.shared_id
AND TableA.foo = 1000;

你不仅要这样做:

ALTER TABLE TableB ADD INDEX (shared_id,bar);

您需要按如下方式向 A 添加索引:

ALTER TABLE TableA ADD INDEX (foo, shared_id);

请执行此操作并提供 EXPLAIN 输出。

另请注意,通过在 (shared_id, bar) 上添加索引,您只是使 (shared_id) 索引变得多余。放下它。

关于mysql - 简单JOIN时如何防止全表扫描?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1203717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com