I have this string "I need red budget car".
I have a table where in column keywords I have comma-separated words. I know that I can use find_in_set
to search if a specific word (ex.budget or car) exists in that column like this for example:
select * from products where find_in_set('budget',keywords) <> 0
However, I can’t find a way to check whether any of the words from the string exist if the keywords column.
Of course, I can separate the string by words and run the above query for each word, but that would increase the execution time, so I am looking for some way to do it in one query.
Update
Maybe I can dynamically create the query and create OR statement for each word of the string, like:
SELECT * FROM products WHERE FIND_IN_SET('I', keywords) OR FIND_IN_SET('need', keywords) OR FIND_IN_SET('a', keywords) OR FIND_IN_SET('budget', keywords) OR FIND_IN_SET('car', keywords)
But there must be a more elegant solution I guess?
2
Answers
I have found the best answer for my case. It's a function that you compare one comma-separated list to another, directly inside the select query.
Here is the function you have to add to MySQL
Then instead of using
FIND_IN_SET()
, you can use theFIND_IN_SET_X()
function that you created.So the query would be
I took this function from this post mysql check if numbers are in a comma separated list
Before using FIND_IN_SET() in MySQL you need to know about the following
before using find_in_Set need to replace space between values with comma-separator works fine.