MySQL 设置变量结果,来自查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11226079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set the variable result, from query
提问by ??? ??????
When I create the saved procedure, i can create some variable yes? for example:
当我创建保存的过程时,我可以创建一些变量是吗?例如:
CREATE PROCEDURE `some_proc` ()
BEGIN
DECLARE some_var INT;
SET some_var = 3;
....
QUESTION: but how to set variable result from the query, that is how to make some like this:
问题:但是如何从查询中设置变量结果,这就是如何制作一些这样的:
DECLARE some_var INT;
SET some_var = SELECT COUNT(*) FROM mytable ;
?
?
回答by Roland Bouman
There are multiple ways to do this.
有多种方法可以做到这一点。
You can use a sub query:
您可以使用子查询:
SET @some_var = (SELECT COUNT(*) FROM mytable);
(like your original, just add parenthesis around the query)
(就像您原来的一样,只需在查询周围添加括号)
or use the SELECT INTO syntax to assign multiple values:
或使用 SELECT INTO 语法来分配多个值:
SELECT COUNT(*), MAX(col)
INTO @some_var, @some_other_var
FROM tab;
The sub query syntax is slightly faster (I don't know why) but only works to assign a single value. The select into syntax allows you to set multiple values at once, so if you need to grab multiple values from the query you should do that rather than execute the query again and again for each variable.
子查询语法稍快(我不知道为什么),但只能分配一个值。select into 语法允许您一次设置多个值,因此如果您需要从查询中获取多个值,您应该这样做,而不是一次又一次地为每个变量执行查询。
Finally, if your query returns not a single row but a result set, you can use a cursor.
最后,如果您的查询返回的不是单行而是结果集,您可以使用游标。
回答by juergen d
The following select statement should allow you to save the result from count(*).
下面的 select 语句应该允许您保存 count(*) 的结果。
SELECT COUNT(*) FROM mytable INTO some_var;