如何使用mysql将查询结果存储在变量中

ibrsph3r  于 2023-11-16  发布在  Mysql
关注(0)|答案(6)|浏览(137)
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

2nbm6dog

2nbm6dog1#

用圆括号将选定内容括起来。

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

字符串

fruv7luv

fruv7luv2#

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

SELECT @total_count:=COUNT(*), @total_price:=SUM(quantity*price) FROM items ...

字符串

zz2j4svz

zz2j4svz3#

使用此

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

字符串
测试和工作正常.

jum4pzuy

jum4pzuy4#

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

字符串

camsedfj

camsedfj5#

如果您想将查询结果保存为临时表,以便在后续查询中重用,请使用MySQL CREATE TEMPORARY TABLE
请参阅: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;

字符串

enxuqcxy

enxuqcxy6#

如果你想在SELECT... WHERE... IN (*here*)中使用变量。
使用GROUP_CONCATfind_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
*/

字符串

相关问题