相关疑难解决方法(0)

MySQL:如何索引"OR"子句

我正在执行以下查询

SELECT COUNT(*)
FROM table
WHERE field1='value' AND (field2 >= 1000 OR field3 >= 2000)
Run Code Online (Sandbox Code Playgroud)

field1上有一个索引,field2和field3上有另一个索引.

我看到MySQL总是选择field1索引然后使用其他两个字段进行连接,这非常糟糕,因为它需要加入146.000行.

关于如何改进这个的建议?谢谢

(在提出试验解决方案后编辑)

基于提出的解决方案,我在使用它时在Mysql上看到过这个.

SELECT COUNT(*) FROM (SELECT * FROM table WHERE columnA = value1
UNION SELECT * FROM table WHERE columnB = value2) AS unionTable;
Run Code Online (Sandbox Code Playgroud)

比执行要慢很多:

SELECT COUNT(*)
FROM table
WHERE (columnA = value1 AND columnB = value2)
      OR (columnA = value1 AND columnC = value3)
Run Code Online (Sandbox Code Playgroud)

有两个合成索引:

index1 (columnA,columnB)
index2 (columnA,columnC)
Run Code Online (Sandbox Code Playgroud)

有趣的是,要求Mysql"解释"它在两种情况下总是使用index1并且不使用index2的查询.

如果我将索引更改为:

index1 (columnB,columnA)
index2 (columnC,columnA)
Run Code Online (Sandbox Code Playgroud)

并查询:

SELECT COUNT(*)
FROM table
WHERE …
Run Code Online (Sandbox Code Playgroud)

mysql indexing composite where

21
推荐指数
2
解决办法
2万
查看次数

标签 统计

composite ×1

indexing ×1

mysql ×1

where ×1