使用WHERE IF和FIND_IN_SET()函数进行mysql查询

时间:2014-07-20 10:56:40

标签: php mysql

我一直在使用以下查询:

 "SELECT * FROM mytable WHERE IF(FIND_IN_SET(column1,'$searchString') > 0,1,0) 
+ IF(FIND_IN_SET(column2, '$searchString') > 0, 1, 0) 
+ IF(FIND_IN_SET(column3, '$searchString') > 0, 1, 0)+ 
IF(FIND_IN_SET(column4, '$searchString') > 0, 1, 0) > 0";

在4次成功匹配之后(以防万一),查询是否会变成以下内容??:

"SELECT * FROM mytable WHERE 1+1+1+1 > 0";

请确保我的假设是否正确。提前谢谢。

2 个答案:

答案 0 :(得分:1)

通常,您会与or进行此类比较,除非您真的想要计算匹配项:

SELECT *
FROM mytable
WHERE (FIND_IN_SET(column1, '$searchString') > 0 OR
       FIND_IN_SET(column2, '$searchString') > 0 OR 
       FIND_IN_SET(column3, '$searchString') > 0 OR
       FIND_IN_SET(column4, '$searchString') > 0
      );

答案 1 :(得分:0)

是的,但你可以缩短

SELECT * FROM mytable 
WHERE 
(
    FIND_IN_SET(column1, '$searchString') > 0 +
    FIND_IN_SET(column2, '$searchString') > 0 + 
    FIND_IN_SET(column3, '$searchString') > 0 + 
    FIND_IN_SET(column4, '$searchString') > 0
) > 0