![](/img/trans.png)
[英]In MySQL can I use an index when I have in “in” condition in my where clause?
[英]MySQL not using index when where condition have if clause
下面是查詢
SELECT * FROM mytable WHERE if(@type=1,col1,col2) = 1420070400;
@type
是一個會話變量。
我在col1
和col2
列上都定義了兩個indexes
,但是mysql在這種情況下不使用。 有什么辦法可以使mysql使用index
?
以下是解釋結果
mysql> explain extended SELECT * FROM mytable WHERE if(@type=1,col1,col2) = 1420070400;
+----+-------------+-----------------+------+---------------+------+---------+------+------+----------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-----------------+------+---------------+------+---------+------+------+----------+-------------+
| 1 | SIMPLE | mytable | ALL | NULL | NULL | NULL | NULL | 1523 | 100.00 | Using where |
+----+-------------+-----------------+------+---------------+------+---------+------+------+----------+-------------+
通常,當列是函數的參數時,數據庫(包括MySQL)不使用索引。
您可以嘗試:
SELECT *
FROM mytable
WHERE (@type = 1 and col1 = 1420070400) or
(@type <> 1 and col2 = 1420070400);
但是,這也不大可能使用索引。 您可以像這樣用詞組查詢:
SELECT *
FROM mytable
WHERE @type = 1 and col1 = 1420070400
UNION ALL
SELECT *
FROM mytable
WHERE @type <> 1 and col2 = 1420070400
UNION ALL
很好,因為實際上只有一個子查詢應該運行。 此版本應使用兩個單獨的索引,一個在mytable(col1)
,另一個在mytable(col2)
。 注意:單個復合索引是不夠的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.