Home > Database > Mysql Tutorial > How to Set User Variables from Query Results in MySQL?

How to Set User Variables from Query Results in MySQL?

Mary-Kate Olsen
Release: 2024-10-28 19:21:29
Original
618 people have browsed it

How to Set User Variables from Query Results in MySQL?

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template