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

时间:2022-04-11 05:52:54
SET @v1 := SELECT COUNT(*) FROM user_rating;
SELECT @v1

When I execute this query with set variable 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

3 个解决方案

#1


101  

Surround that select with parentheses.

用圆括号括住选择。

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

#2


22  

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.

另外,如果您想一次通过一个查询设置多个变量,您可以使用其他语法来设置像这样的变量:选择@varname:=值。

A practical example:

一个实际的例子:

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

#3


8  

use this

使用这个

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

tested and workes fine...

测试和附件细……

#1


101  

Surround that select with parentheses.

用圆括号括住选择。

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

#2


22  

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.

另外,如果您想一次通过一个查询设置多个变量,您可以使用其他语法来设置像这样的变量:选择@varname:=值。

A practical example:

一个实际的例子:

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

#3


8  

use this

使用这个

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

tested and workes fine...

测试和附件细……