是否可以根据MySQL中的查询结果设置用户变量?
我想要实现的是这样的事情(我们可以假设USER和GROUP都是唯一的):
USER
GROUP
set @user = 123456; set @group = select GROUP from USER where User = @user; select * from USER where GROUP = @group;
请注意,我知道有可能,但我不希望使用嵌套查询。
是的,但是您需要将变量分配移至查询中:
SET @user := 123456; SELECT @group := `group` FROM user WHERE user = @user; SELECT * FROM user WHERE `group` = @group;
测试用例:
CREATE TABLE user (`user` int, `group` int); INSERT INTO user VALUES (123456, 5); INSERT INTO user VALUES (111111, 5);
结果:
SET @user := 123456; SELECT @group := `group` FROM user WHERE user = @user; SELECT * FROM user WHERE `group` = @group; +--------+-------+ | user | group | +--------+-------+ | 123456 | 5 | | 111111 | 5 | +--------+-------+ 2 rows in set (0.00 sec)
请注意,对于SET,=或:=可用作分配运算符。但是,在其他语句中,赋值运算符必须为:=并且不是,=因为=在非SET语句中将其视为比较运算符。
SET
=
:=
更新:
除了下面的评论,您还可以执行以下操作:
SET @user := 123456; SELECT `group` FROM user LIMIT 1 INTO @group; SELECT * FROM user WHERE `group` = @group;