Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store Query Result in variable using mysql

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 
like image 306
Query Master Avatar asked Apr 09 '12 07:04

Query Master


People also ask

Can we store a query in a variable?

Yup, this is possible of course.

How do you store SQL query result in a variable in PHP?

Use the following syntax : $result= mysql_query(".. your query.."); Note that this variable can also store multiple rows depending on your query. Also note that statements other than "select" will return the no of rows affected.

How do you store a query result in a variable in Python?

First of all, c. fetchall() retrieves ALL the results from your query, we'll put them in a variable called rows . Then we create a iterator (the thing you tried to do with the while loop) by doing for row in rows . Then we simply print each row.


2 Answers

Surround that select with parentheses.

SET @v1 := (SELECT COUNT(*) FROM user_rating); SELECT @v1; 
like image 108
Sergio Tulentsev Avatar answered Sep 18 '22 18:09

Sergio Tulentsev


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 ... 
like image 28
Yirkha Avatar answered Sep 19 '22 18:09

Yirkha