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

当我使用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
4

4 回答 4

163

用括号括住该选择。

SET @v1 := (SELECT COUNT(*) FROM user_rating);
SELECT @v1;
于 2012-04-09T07:50:38.840 回答
39

此外,如果您想通过一个查询一次设置多个变量,您可以使用另一种语法来设置变量,如下所示SELECT @varname:=value

一个实际的例子:

SELECT @total_count:=COUNT(*), @total_price:=SUM(quantity*price) FROM items ...
于 2014-04-25T00:19:07.443 回答
10

用这个

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

经过测试并且工作正常...

于 2014-04-27T22:45:53.573 回答
3
Select count(*) from table_name into @var1; 
Select @var1;
于 2019-12-17T10:37:27.770 回答