【发布时间】:2021-12-08 02:25:31
【问题描述】:
我有这个架构
create table table1
(
id int auto_increment primary key,
name varchar(2) null,
position int null,
);
create index table1_position
on table1 (position);
create table table_2
(
id int auto_increment primary key,
table1_id int null,
position int null,
constraint table_2_ibfk_1
foreign key (table1_id) references table1 (id)
);
create index ix_table_2_position
on table_2 (position);
create index table1_id
on table_2 (table1_id);
所以我在每个表的position 列上添加了两个索引。
现在我需要在 BOTH 表中查找一系列位置(然后加入并应用 OR 查询)
所以我有这个问题
SELECT *
FROM table_1
INNER JOIN table_2 ON table_1.id = table_2.table1_id
WHERE table_1.position BETWEEN 5000 AND 5500
OR table_2.position BETWEEN 5000 AND 5500
但解释查询输出给了我 ALL(全表扫描)
id 1
select_type SIMPLE
table table_1
partitions
type ALL
possible_keys PRIMARY,table1_position
key
key_len
ref
rows 9929
filtered 100.0
Extra
如果我更改为 AND 如果给我预期的范围索引扫描
SELECT *
FROM table_1
INNER JOIN table_2 ON table_1.id = table_2.table1_id
WHERE table_1.position BETWEEN 5000 AND 5500
AND table_2.position BETWEEN 5000 AND 5500
id 1
select_type SIMPLE
table table_1
partitions
type range
possible_keys PRIMARY,pos_idx2
key pos_idx2
key_len 5
ref
rows 1
filtered 100.0
Extra Using index condition
但是我在这里需要OR 语句...我怎么能让mysql 使用范围扫描索引来执行OR 语句?我可以在这里改进我的索引吗(我考虑过在 position 和 table1_id 上使用多值索引 - 外键,但它没有帮助,它执行了全表扫描)。
【问题讨论】:
-
你可以添加一些插入,以便我可以在我的 sql fiddle 中测试它吗?
-
table_2.variant_id 未反映在表架构中
-
@ProGu 我修好了对不起,阴影错误
-
粗略地说,t where x or y is t where x union t where y。这篇文章是一个常见问题解答。请在考虑发布之前阅读手册和谷歌任何错误消息和许多清晰、简洁和准确的问题/问题/目标的措辞,带有和不带有您的特定名称/字符串/数字、“site:stackoverflow.com”和标签;阅读许多答案。反映你的研究。 How to AskHelp centerPS minimal reproducible example
标签: mysql sql join indexing sql-optimization