Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using mysql variable to hold comma separated value to be used for where in clause

I have to run a query like this (query 1) -

select something from sometable where someId in (1,2,3)

I would like to keep a variable for the IDs part, like this (query 2) -

set @myIds = "1,2,3";
select something from sometable where someId in (@myIds);

But this does not give the expected result (gives an empty result set), and no query error as well.

I checked that if I wrap the comma separated IDs inside quotes, the query results an empty result set (query 3) -

select something from sometable where someId in ("1,2,3");

I guess when I am using variable @myIds like I showed above (query 2), it is evaluating to the above query (query 3).

like image 810
Sandeepan Nath Avatar asked Sep 17 '13 07:09

Sandeepan Nath


People also ask

Where clause with comma separated values in MySQL?

To perform where clause on comma separated string/values, MySQL has an inbuilt function called FIND_IN_SET which will search for values within a comma separated values. You can also use IN operator to achieve the same but there are some limitations with IN operator which I will show below.

Can we store comma separated values in MySQL?

A better answer: Don't store a list of comma separated values. Store one value per row, and use a SELECT query with GROUP_CONCAT to generate the comma separated value when you access the database. Is group_concat a mysql only extension?


Video Answer


2 Answers

You need to have a dynamic sql on this,

SET @myIds = '1,2,3';
SET @sql = CONCAT('select something from sometable where someId in (',@myIds,')');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
  • SQLFiddle Demo
like image 169
John Woo Avatar answered Oct 29 '22 22:10

John Woo


The proper (and also more complicated) way to do that would be a temp table:

DROP TEMPORARY TABLE IF EXISTS `some_tmp_table`
CREATE TEMPORARY TABLE `some_tmp_table` (
    `id` INT(10) UNSIGNED NOT NULL
) ENGINE=MEMORY #memory engine is optional...

Insert your ID's the temp table

INSERT INTO some_tmp_table VALUES (1),(2),(3)...

and then use a JOIN instead of IN().

SELECT something 
FROM sometable s
JOIN some_tmp_table ts ON ts.id = s.someId

The other way is to use dynamic SQL as the other answer suggests. It might be simpler for you to generate the dynamic SQL in your app, but you can do it in MySQL too.

like image 31
Vatev Avatar answered Oct 29 '22 23:10

Vatev