0

I need to define a list of variables to use in multiple MySQL queries.

The variable will be a list of mails. I have tried to define it in different ways but it always gives me error in the construction.

SET @listamails='mail1@gmail.com,mail2@gmail.com';

Select * from user WHERE mail IN (@listamails);

Any ideas?

Thank you

V. G.
  • 3
  • 1
  • 1
    You need prepared statement for this – Shadow Sep 08 '17 at 11:22
  • Thank you. I had read that thread but I did not see that it solved my problem. Now I have seen it clear. My final code: SET @listamails='mail1@gmail.com,mail2@gmail.com'; Select * from user WHERE FIND_IN_SET(email, @listamails); – V. G. Sep 08 '17 at 21:32

2 Answers2

0

You cannot pass in a list to IN using a single variable. The simplest solution in MySQL is find_in_set():

Select u.*
from user u
where find_in_set(mail, @listamails) > 0;

However, this cannot take advantage of an index. For that, you might want to use dynamic SQL.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
-1

Try this

SET @listamails='mail1@gmail.com','mail2@gmail.com';

Select * from user WHERE mail IN (@listamails);
Suraj
  • 363
  • 2
  • 16