Query Master
Query Master

Reputation: 7097

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

Upvotes: 120

Views: 207844

Answers (6)

zhuhang.jasper
zhuhang.jasper

Reputation: 4475

If you're trying to use the variable inside SELECT... WHERE... IN (*here*).

Use GROUP_CONCAT and find_in_set.

-- initialise with a comma-separated string
SET @emails = '[email protected],[email protected],[email protected]';

-- search condition
SELECT * FROM customer WHERE find_in_set(email, @emails);

-- or, you can initialise the variable using query results
SELECT GROUP_CONCAT(phone) INTO @activeCustomerPhones FROM customer WHERE status = 'ACTIVE';

SELECT * FROM transaction WHERE find_in_set(phone, @activeCustomerPhones);

/* 
customer:
- phone
- email
- status 

transaction:
- phone
*/

Upvotes: 1

zhuhang.jasper
zhuhang.jasper

Reputation: 4475

Use MySQL CREATE TEMPORARY TABLE if you want to save query result as a temp table for reuse in subsequent queries.

See: https://dev.mysql.com/doc/refman/8.0/en/create-temporary-table.html

-- begin: drop first just in case
DROP TEMPORARY TABLE IF EXISTS myDb.temp_variable; 
CREATE TEMPORARY TABLE myDb.temp_variable SELECT * FROM myDb.student ORDER BY id DESC LIMIT 25;

-- your scripts
SELECT * FROM myDb.temp_variable;

-- end: drop to prevent cached values accessed by other queries
DROP TEMPORARY TABLE IF EXISTS myDb.temp_variable; 

Upvotes: 2

Aman Maurya
Aman Maurya

Reputation: 1325

use this

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

tested and workes fine...

Upvotes: 12

Kesha Viveki
Kesha Viveki

Reputation: 209

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

Upvotes: 8

Yirkha
Yirkha

Reputation: 13868

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

Upvotes: 46

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230521

Surround that select with parentheses.

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

Upvotes: 184

Related Questions