Home > Database > Mysql Tutorial > How to Correctly Format MySQL Variables for Use in a 'NOT IN' Clause?

How to Correctly Format MySQL Variables for Use in a 'NOT IN' Clause?

Mary-Kate Olsen
Release: 2024-12-31 20:32:10
Original
900 people have browsed it

How to Correctly Format MySQL Variables for Use in a

MySQL Variable Format for a "NOT IN" List of Values

When attempting to exclude certain values in a MySQL query using a "NOT IN" list, assigning a variable to the excluded values can be a convenient solution. However, ensuring the correct variable format is crucial.

As described in your query, you tried assigning the variable '@idcamposexcluidos' with different formats:

  • SET @idcamposexcluidos='817,803,495';
  • SET @idcamposexcluidos='(817,803,495)';
  • SET @idcamposexcluidos=817,803,495;

However, none of these formats work as expected. The reason is that the "IN" clause requires separate values, not a single string. Therefore, the query:

WHERE id_campo not in (@idcamposexcluidos)
Copy after login

effectively becomes:

WHERE id_campo not in ('817,803,495')
Copy after login

which is incorrect. The values should be provided as separate string literals:

WHERE id_campo not in ('817','803','495')
Copy after login

To overcome this issue, there are two options:

  1. Dynamic SQL: Create the query dynamically using a concatenation of the excluded values.
  2. MySQL FIND_IN_SET() Function: Use the FIND_IN_SET() function to check if the value exists in the comma-separated list of excluded values, as shown below:
SET @idcamposexcluidos='817,803,495';
...
WHERE FIND_IN_SET(id_campo, @idcamposexcluidos) = 0
Copy after login

Note that using the FIND_IN_SET() function may impair index usage.

The above is the detailed content of How to Correctly Format MySQL Variables for Use in a 'NOT IN' Clause?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template