MySQL中用户定义变量的奇怪行为

时间:2022-11-11 05:00:45

I've noticed something odd about user-defined variables:

我注意到用户定义的变量有些奇怪:

Lets say I have this table:

可以说我有这张桌子:

 num_table
+---------+
| numbers |
|    3    |
|    6    |
|    9    |
+---------+

I can create a comma-separated list and store it in a user-defined variable like so:

我可以创建一个以逗号分隔的列表并将其存储在用户定义的变量中,如下所示:

SELECT @var := GROUP_CONCAT `numbers` from num_table;

Which will assign the value 3,6,9 to @var.

将值3,6,9分配给@var。

And here is the odd part. Running

这是奇怪的部分。运行

SELECT 3 IN (@var)

returns 1, but running

返回1,但正在运行

SELECT 6 IN (@var)

returns 0.

返回0。

It seems to me it should either work or not work. Any idea why it works only with the first number in the list?

在我看来它应该工作或不工作。知道为什么它只适用于列表中的第一个数字吗?

2 个解决方案

#1


2  

You cannot use IN () with a variable and have that variable be treated as a list - only actual lists (perhaps of variables) can be used - i.e. IN (1, 2, 3) or IN (@var1, @var2, @var3)

你不能将IN()与变量一起使用并将该变量视为列表 - 只能使用实际列表(可能是变量) - 即IN(1,2,3)或IN(@ var1,@ var2,@ VAR3)

Neither should work if @var contains '3, 6, 9' - so I suspect @var contains '3', though - can you verify its contents?

如果@var包含'3,6,9',那么两者都不应该工作 - 所以我怀疑@var包含'3',但是你可以验证它的内容吗?

Martin might be on to something with the casting - I'd bet '3' IN (@var) returns nothing

马丁可能正在投球 - 我敢打赌'3'IN(@var)什么都不回

#2


1  

You cannot use IN () with a string variable - but you can use FIND_IN_SET() instead, which serves exactly this purpose:

您不能将IN()与字符串变量一起使用 - 但您可以使用FIND_IN_SET()来实现此目的:

SELECT FIND_IN_SET(6, @var)

returns 2 - second position

返回2 - 秒位置

SELECT FIND_IN_SET(7, @var)

returns NULL - no match

返回NULL - 不匹配

#1


2  

You cannot use IN () with a variable and have that variable be treated as a list - only actual lists (perhaps of variables) can be used - i.e. IN (1, 2, 3) or IN (@var1, @var2, @var3)

你不能将IN()与变量一起使用并将该变量视为列表 - 只能使用实际列表(可能是变量) - 即IN(1,2,3)或IN(@ var1,@ var2,@ VAR3)

Neither should work if @var contains '3, 6, 9' - so I suspect @var contains '3', though - can you verify its contents?

如果@var包含'3,6,9',那么两者都不应该工作 - 所以我怀疑@var包含'3',但是你可以验证它的内容吗?

Martin might be on to something with the casting - I'd bet '3' IN (@var) returns nothing

马丁可能正在投球 - 我敢打赌'3'IN(@var)什么都不回

#2


1  

You cannot use IN () with a string variable - but you can use FIND_IN_SET() instead, which serves exactly this purpose:

您不能将IN()与字符串变量一起使用 - 但您可以使用FIND_IN_SET()来实现此目的:

SELECT FIND_IN_SET(6, @var)

returns 2 - second position

返回2 - 秒位置

SELECT FIND_IN_SET(7, @var)

returns NULL - no match

返回NULL - 不匹配