mysql IN()和LIKE在一起

时间:2017-12-14 17:39:55

标签: mysql search sql-like

我知道我可以重写这个查询

SELECT * FROM [table] WHERE 
(column1 = 'dog' AND column2 = 1) OR
(column1 = 'cat' AND column2 = 2) OR
(column1 = 'mouse' AND column3 = 3) OR
(column1 = 'wolf' AND column4 = 4);

以更好的方式:

SELECT  *
FROM    [table]
WHERE   (column1, column2) IN (('dog', 1), ('cat', 2), ('mouse', 3), 
('wolf', 4));

此查询的方式类似:

SELECT * FROM [table] WHERE 
(column1 = 'dog' AND column2 like '%red%') OR
(column1 = 'cat' AND column2 like '%blue%') OR
(column1 = 'mouse' AND like '%red%') OR
(column1 = 'wolf' AND column2 like '%green%');

1 个答案:

答案 0 :(得分:0)

没有。元组列表例如。

(a,b) IN ( (2,3) , (5,7) , (11,13) )

仅用于相等比较。

但是还有其他方法来编写查询,其中一些可能比其他方法表现更好,具体取决于合适索引的可用性......例如。

SELECT t1.* FROM mytable t1 WHERE t1.column1 = 'dog'   AND t1.column2 LIKE '%red%'
 UNION ALL
SELECT t2.* FROM mytable t2 WHERE t2.column1 = 'cat'   AND t2.column2 LIKE '%blue%'
 UNION ALL
SELECT t3.* FROM mytable t3 WHERE t3.column1 = 'mouse' AND t3.column2 LIKE '%red%'
 UNION ALL
SELECT t4.* FROM mytable t4 WHERE t4.column1 = 'wolf'  AND t4.column2 LIKE '%green%'