Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple values in mysql variable

Tags:

mysql

The following works as expected when there is a single value stored in a variable.

SET @a := "20100630";
SELECT * FROM wordbase WHERE verified = @a;

But it does not work when there are multiple values stored in a variable.

SET @a := "'20100630', '20100701' ";
SELECT * FROM wordbase WHERE verified in (@a);

Do I need to use prepared statements for this?

like image 709
shantanuo Avatar asked Jul 01 '10 09:07

shantanuo


People also ask

How do I assign multiple values to a variable in MySQL?

The following works as expected when there is a single value stored in a variable. SET @a := "20100630"; SELECT * FROM wordbase WHERE verified = @a; But it does not work when there are multiple values stored in a variable. SET @a := "'20100630', '20100701' "; SELECT * FROM wordbase WHERE verified in (@a);

How do I SELECT multiple items in MySQL?

To select multiple values, you can use where clause with OR and IN operator.

Can you use variables in MySQL?

Mysql also supports the concept of User-defined variables, which allows passing of a value from one statement to another. A user-defined variable in Mysql is written as @var_name where, var_name is the name of the variable and can consist of alphanumeric characters, ., _, and $.


1 Answers

There's good solution described here: https://stackoverflow.com/a/11957706/1523961

So can use something like this:

SET @a := '20100630,20100701';
SELECT * FROM wordbase WHERE FIND_IN_SET(verified, @a);

Also, if you're selecting the ids for @a from another table, you can come up with following:

SET @a := (SELECT GROUP_CONCAT(id) FROM someTable where yourBooleanExpressionHere);
SELECT * FROM wordbase WHERE FIND_IN_SET(verified, @a);
like image 167
grinderX19 Avatar answered Sep 28 '22 03:09

grinderX19