MySQL variable format for the NOT IN list of values

Goes crazy trying to set a variable in a query like:

SET @idcamposexcluidos='817,803,495'; 

so i can use it on

 WHERE id_campo not in (@idcamposexcluidos) 

I tried to define the variable in different formats without any luck and did not seem to find a specific example for the above:

 SET @idcamposexcluidos='(817,803,495)'; ... WHERE id_campo not in @idcamposexcluidos SET @idcamposexcluidos=817,803,495; 

without success. It either returns an error or ignores the values.

+46
sql mysql in-clause
Aug 14 2018-12-12T00:
source share
3 answers

You cannot use an IN clause like this. It compiles to a single string in your IN clause. But the IN clause requires separate values.

 WHERE id_campo not in (@idcamposexcluidos) 

compiles to

 WHERE id_campo not in ('817,803,495') 

but it should be

 WHERE id_campo not in ('817','803','495') 

To overcome this or use dynamic SQL or MySQL, you can use FIND_IN_SET :

 SET @idcamposexcluidos='817,803,495'; ... WHERE FIND_IN_SET(id_campo, @idcamposexcluidos) = 0 
+78
Aug 14 '12 at 17:35
source share

if you use mysql> 5.1 you can use:

 CREATE TYPE lista as ( clave int4, valor int4 ); CREATE OR REPLACE FUNCTION test(IN vArray lista[]) ... WHERE FIND_IN_SET(id_campo, vArray) ... 

otherwise you can use the trick:

 WHERE id_campo IN ( SELECT 817 as valor UNION ALL SELECT 803 as valor UNION ALL SELECT 495 as valor) 
+1
Aug 14 '12 at 18:19
source share

Using CONCAT() , a channel separator (instead of a comma), and a bit of โ€œinverse logicโ€, you can use the variable in your NOT IN list, but instead with NOT LIKE !

Example:

 SET @idcamposexcluidos = '|817|803|495|'; SELECT * FROM your_table WHERE @idcamposexcluidos NOT LIKE CONCAT('%|', id_campo, '|%'); 

This should work with both string and numeric columns.

0
Aug 14 '12 at 17:56
source share



All Articles