How to INSERT list containing strings into variable and add them to IN clause later in MySQL

I have got a question. How could I add list of strings to variable if I want to use them in IN clause.

Example:

I have got query containing IN clause like:

WHERE products_name IN ("Product1", "Product2", "Product3")

I would like to add this to variable like:

SET @products = ("Product1", "Product2", "Product3")

so I coulde use it like:

WHERE products_name IN (@products)

It returns error or empty results. What am I doing wrong?

Answer

SET @products = 'Product1,Product2,Product3';

and

... WHERE FIND_IN_SET(products_name, @products) ...

Pay attention – there is no spaces after commas in CSV value.

PS. This technique does not allow to use indices.

Leave a Reply

Your email address will not be published. Required fields are marked *