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
答案 0 :(得分:122)
用括号选择的环绕声。
SET @v1 := (SELECT COUNT(*) FROM user_rating);
SELECT @v1;
答案 1 :(得分:28)
此外,如果您想通过一个查询一次设置多个变量,则可以使用其他语法设置如下所示的变量:SELECT @varname:=value
。
一个实际的例子:
SELECT @total_count:=COUNT(*), @total_price:=SUM(quantity*price) FROM items ...
答案 2 :(得分:8)
使用此
SELECT weight INTO @x FROM p_status where tcount=['value'] LIMIT 1;
测试并且工作得很好......
答案 3 :(得分:1)
我正在尝试在这里做类似的事情。但是,我的 SQL 语法出现错误:
SET @dc = (SELECT CONCAT('DROP SCHEMA IF EXISTS ', SCHEMA_NAME,';') FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = 'tc1-student');
SELECT @dc;
PREPARE drop_dc FROM @dc;
EXECUTE drop_dc;
DEALLOCATE PREPARE drop_dc;
实际的 SELECT 查询确实正常工作。但是当设置尝试从@dc 变量准备语句时,我收到一个 SQL 语法错误。这里有什么突出的吗?
答案 4 :(得分:0)
Select count(*) from table_name into @var1;
Select @var1;