Is it possible to set a user variable based on the result of a query in MySQL?
What I want to achieve is something like this (we can assume that both USER and GROUP are unique):
set @user = 123456;
set @group = select GROUP from USER where User = @user;
select * from USER where GROUP = @group;
Please note that I know it’s possible but I do not wish to do this with nested queries.
Yes, but you need to move the variable assignment into the query:
Test case:
Result:
Note that for
SET, either=or:=can be used as the assignment operator. However inside other statements, the assignment operator must be:=and not=because=is treated as a comparison operator in non-SET statements.UPDATE:
Further to comments below, you may also do the following: