Assigning user-defined variables based on query results enhances database manipulation capabilities. This article explores a method to achieve this in MySQL without resorting to nested queries.
Contrary to popular belief, user variable assignment can be integrated directly into queries. The assignment operator for SET statements is either = or :=. However, := must be used within other statements, as = is reserved for comparisons.
To illustrate this technique, let's assume USER and GROUP are unique. The following query sequence showcases the functionality:
SET @user := 123456; SELECT @group := `group` FROM USER WHERE user = @user; SELECT * FROM USER WHERE `group` = @group;
Using a sample table with the following data:
CREATE TABLE user (`user` int, `group` int); INSERT INTO user VALUES (123456, 5); INSERT INTO user VALUES (111111, 5);
The query yields the following result:
-------- ------- | user | group | -------- ------- | 123456 | 5 | | 111111 | 5 | -------- -------
As an alternative, the following syntax can be employed:
SET @user := 123456; SELECT `group` FROM user LIMIT 1 INTO @group; SELECT * FROM user WHERE `group` = @group;
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3