Setting User Variables from Query Results in MySQL
It is possible to populate user variables with the output of a query in MySQL. To achieve this, incorporate the variable assignment within the query itself. For example:
<code class="mysql">SET @user := 123456; SELECT @group := `group` FROM user WHERE user = @user; SELECT * FROM user WHERE `group` = @group;</code>
Test this by creating a table:
<code class="mysql">CREATE TABLE user (`user` int, `group` int); INSERT INTO user VALUES (123456, 5); INSERT INTO user VALUES (111111, 5);</code>
The resulting output demonstrates how the user variable @group is populated with the appropriate group ID:
<code class="mysql">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)</code>
Note: You can use either = or : = as the assignment operator in SET statements. However, in other contexts, only : = should be used as = is a comparator in those instances.
Update:
An alternative approach is to utilize the LIMIT clause:
<code class="mysql">SET @user := 123456; SELECT `group` FROM user LIMIT 1 INTO @group; SELECT * FROM user WHERE `group` = @group;</code>
The above is the detailed content of How to Set User Variables from Query Results in MySQL?. For more information, please follow other related articles on the PHP Chinese website!