“NOT IN”值列表的 MySQL 变量格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11957643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MySQL variable format for a "NOT IN" list of values
提问by luison
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.
没有成功。它要么返回错误,要么忽略这些值。
回答by juergen d
You can't use the IN
clause like that. It compiles to a singlestring in your IN
clause. But an IN
clause needs separatevalues.
你不能这样使用IN
子句。它在您的子句中编译为单个字符串IN
。但是IN
子句需要单独的值。
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:
要克服这个问题,请使用动态 SQL 或在 MySQL 中使用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.
但是使用像这样的函数FIND_IN_SET()
不能使用索引。
回答by randiel
if you use mysql > 5.1, you can use:
如果您使用 mysql > 5.1,则可以使用:
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)
回答by newfurniturey
By using CONCAT()
, a pipe-separator (instead of a comma), and a little "reverse logic", you can use a variable in your NOT IN
list, but instead - by using NOT LIKE
!
通过使用CONCAT()
、管道分隔符(而不是逗号)和一些“反向逻辑”,您可以在NOT IN
列表中使用一个变量,但是 - 通过使用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 alike.
这应该适用于字符串和数字列。