简体   繁体   中英

mysql query with WHERE IF and FIND_IN_SET() function

I have been using the following query:

 "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";

So (in case) after 4 successful matches, does the query becomes the following??:

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

Please ensure me whether my assumption is right. thanks in advance.

Normally, you would do this type of comparison with or unless you want really want to count the matches:

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
      );

Yes, but you can make this shorter

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM