Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL variable format for a "NOT IN" list of values

Going crazy trying to set a variable in a query of type:

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

so i can then use it on a

WHERE id_campo not in (@idcamposexcluidos) 

I've tried defining the variable in different formats with no luck and don't seem to find an specific example for the above:

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

with no success. It either returns an error or ignores the values.

like image 605
luison Avatar asked Aug 14 '12 17:08

luison


People also ask

What does := do in MySQL?

This means you can use := in any valid SQL statement (not just in SET statements) to assign a value to a variable. While it is also possible both to set and to read the value of the same variable in a single SQL statement using the := operator, this is not recommended.

How do I exclude something in MySQL?

To check records which are NULL, use IS NULL. However, to exclude any of the records, use the NOT IN clause. Use both of them in the same query.

How do you reference a variable in MySQL?

User variables are written as @ var_name , where the variable name var_name consists of alphanumeric characters, . , _ , and $ . A user variable name can contain other characters if you quote it as a string or identifier (for example, @'my-var' , @"my-var" , or @`my-var` ). User-defined variables are session specific.

How do you assign a value to a variable in MySQL?

Variables are written as "@var_name" where "var_name" can be replaced by any alphanumeric character or the "-", "_" and "$" symbols. They can be assigned using the "=" or ":=" characters. The value can be any datatype supported by the MySQL database.


2 Answers

You can't use the IN clause like that. It compiles to a single string in your IN clause. But an IN clause needs 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 either use dynamic SQL or in MySQL you could use FIND_IN_SET:

SET @idcamposexcluidos='817,803,495'; ... WHERE FIND_IN_SET(id_campo, @idcamposexcluidos) = 0 

but using a function like FIND_IN_SET() can not make use of indexes.

like image 197
juergen d Avatar answered Sep 23 '22 19:09

juergen d


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) ... 

in other case you can use a trick:

WHERE id_campo IN ( SELECT 817 as valor UNION ALL                  SELECT 803 as valor UNION ALL                     SELECT 495 as valor) 
like image 29
randiel Avatar answered Sep 20 '22 19:09

randiel