简体   繁体   中英

Search post array in comma separated column value

Table - Column Data

id | filter_data |
---|---------------
1  |2,3,45,67,4  |
2  |2,3,55,33,5,7|

Post variable from form as

$search_filter = {2,3,4,5}

How can I get the id which are in the search filter

Solution 1:

As @Jens commented, it's a bad DB design to store values as CSV. So the first solution would be to change your DB design since I don't really know what you're storing and what is the purpose of your DB/code I can't write a scheme or give any meaningful suggestion.

Solution 2:

Use MySQL's find_in_set function.

Returns a value in the range of 1 to N if the string str is in the string list strlist consisting of N substrings. A string list is a string composed of substrings separated by “,” characters. If the first argument is a constant string and the second is a column of type SET, the FIND_IN_SET() function is optimized to use bit arithmetic. Returns 0 if str is not in strlist or if strlist is the empty string. Returns NULL if either argument is NULL. This function does not work properly if the first argument contains a comma (“,”) character.

SELECT id FROM table
WHERE FIND_IN_SET(searchFilterHere, filter_data)

Solution 3:

You can use the LIKE operator. (Some members probably will kill me for suggesting it, but if you don't want to change your DB design - this is a creative option).

Let's check the following code:

SELECT id FROM table WHERE filter_data LIKE '%2,%'

The problem is that it will return the id of a field with 22, in the filter_data's column. Therefore, you'll have to change the data under that column so , will appear also as the first and last characters. For instance:

id | filter_data   |
---|---------------
1  |,2,3,45,67,4,  |
2  |,2,3,55,33,5,7,|

And now you can do the following:

SELECT id FROM table WHERE filter_data LIKE '%,2,%'

If you have multiple "search filters" you can combine the LIKE s with an OR operator.

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