How to store Query Result in variable using mysql

2019-01-16 05:24发布

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

When I execute this query with set variable this error is shown.

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条回答
Evening l夕情丶
2楼-- · 2019-01-16 05:42

Surround that select with parentheses.

SET @v1 := (SELECT COUNT(*) FROM user_rating);
SELECT @v1;
查看更多
爷的心禁止访问
3楼-- · 2019-01-16 05:47

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.

A practical example:

SELECT @total_count:=COUNT(*), @total_price:=SUM(quantity*price) FROM items ...
查看更多
Fickle 薄情
4楼-- · 2019-01-16 05:51

use this

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

tested and workes fine...

查看更多
登录 后发表回答