How to store Query Result in variable using mysql

MysqlDatabaseVariablesSet

Mysql Problem Overview


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

Mysql Solutions


Solution 1 - Mysql

Surround that select with parentheses.

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

Solution 2 - Mysql

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 ...

Solution 3 - Mysql

use this

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

tested and workes fine...

Solution 4 - Mysql

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionQuery MasterView Question on Stackoverflow
Solution 1 - MysqlSergio TulentsevView Answer on Stackoverflow
Solution 2 - MysqlYirkhaView Answer on Stackoverflow
Solution 3 - MysqlAman MauryaView Answer on Stackoverflow
Solution 4 - MysqlKesha VivekiView Answer on Stackoverflow