Home >Database >Mysql Tutorial >How to Use MySQL's 'NOT IN' Clause with a List of Values?
Question:
How do you define a MySQL variable with a list of values for use in a "NOT IN" clause, effectively excluding multiple values from a query?
Answer:
When constructing a "NOT IN" clause with a list of values, it's essential to avoid using the entire list as a single string within the clause. MySQL compiles it as a unified string, while the "NOT IN" clause requires individual values. Consider the following example:
WHERE id_campo NOT IN (@idcamposexcluidos)
This compiles to:
WHERE id_campo NOT IN ('817,803,495')
However, the correct syntax would be:
WHERE id_campo NOT IN ('817', '803', '495')
To overcome this, there are two common approaches:
WHERE FIND_IN_SET(id_campo, @idcamposexcluidos) = 0
It's important to note that using the FIND_IN_SET() function may impact performance if indexes are employed on the 'id_campo' column.
The above is the detailed content of How to Use MySQL's 'NOT IN' Clause with a List of Values?. For more information, please follow other related articles on the PHP Chinese website!