MySQL 如何使用mysql将查询结果存储在变量中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10070406/
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 12:53:10  来源:igfitidea点击:

How to store Query Result in variable using mysql

mysqldatabasevariablesset

提问by Query Master

SET @v1 := SELECT COUNT(*) FROM user_rating;
SELECT @v1

When I execute this query with setvariable this error is shown.

当我使用set变量执行此查询时,会显示此错误。

Error Code : 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
near 'SELECT count(*) FROM user_rating' at line 1

Execution Time : 00:00:00:000
Transfer Time  : 00:00:00:000
Total Time     : 00:00:00:000

(1 row(s) returned)
Execution Time : 00:00:00:343
Transfer Time  : 00:00:00:000
Total Time     : 00:00:00:343

回答by Sergio Tulentsev

Surround that select with parentheses.

用括号将 select 括起来。

SET @v1 := (SELECT COUNT(*) FROM user_rating);
SELECT @v1;

回答by Yirkha

Additionally, if you want to set multiple variables at once by one query, you can use the other syntax for setting variables which goes like this: SELECT @varname:=value.

此外,如果你想通过一个查询一次设置多个变量,你可以用其他的语法,用于设置是这样的变量:SELECT @varname:=value

A practical example:

一个实际例子:

SELECT @total_count:=COUNT(*), @total_price:=SUM(quantity*price) FROM items ...

回答by Aman Maurya

use this

用这个

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

tested and workes fine...

经测试,工作正常...

回答by Kesha Viveki

Select count(*) from table_name into @var1; 
Select @var1;