将查询结果设置为 MySQL 中的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10741612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 13:31:39  来源:igfitidea点击:

Set the result of a query to a variable in MySQL

mysqlvariables

提问by NateSHolland

This should be a simple syntax thing: I'm trying to set a variable in MySQL equal to the result of a query for instance:

这应该是一个简单的语法事情:例如,我试图在 MySQL 中设置一个等于查询结果的变量:

SET @variable1 = SELECT salary FROM employee_info WHERE emp_id = 12345678;

Basically I want the salary from that employee to be stored as a variable that I can then manipulate and add.

基本上,我希望将该员工的工资存储为一个变量,然后我可以对其进行操作和添加。

What would the correct syntax for this be because I can't get it to work.

正确的语法是什么,因为我无法让它工作。

回答by Damith

SELECT salary INTO @variable1 FROM employee_info WHERE emp_id = 12345678 LIMIT 1;

or

或者

SET @variable1 = (SELECT salary FROM employee_info WHERE emp_id = 12345678 LIMIT 1);

SELECT @variable1;

回答by Olias

You can even fill multiple variables in a single query.

您甚至可以在单个查询中填充多个变量。

SELECT salary, salary_group INTO @var1, @var2 FROM employee_info WHERE emp_id = 12345678;

回答by Adam Fili

You are quite close to the right syntax. Here it is:

您非常接近正确的语法。这里是:

SET @variable1 = (SELECT salary FROM employee_info WHERE emp_id = 12345678);

and then print the variable like this:

然后像这样打印变量:

SELECT @variable1;

回答by Ravi Parekh

SELECT @code:=salary FROM employee_info WHERE emp_id = 12345678;

To check salary,

检查工资,

SELECT @code;

The result of salary will be initialized in code.

工资的结果将在code.

More Information

更多信息

回答by kavitha Reddy

Set the result of a query to a variable in MySQL

将查询结果设置为 MySQL 中的变量

Select  @Amount1:=  Amount FROM table where id=57703;

回答by Aman Maurya

use this

用这个

SELECT weight INTO @x FROM p_status where tcount=['value'] LIMIT 1;

tested and workes fine...

经测试,工作正常...

回答by Rahul

select @variable1 := salary FROM employee_info WHERE emp_id = 12345678;