mysql>SET @t1=1, @t2=2, @t3:=4;
mysql>SELECT @t1, @t2, @t3, @t4 := @t1+@t2+@t3;
+------+------+------+--------------------+ | @t1 | @t2 | @t3 | @t4 := @t1+@t2+@t3 | +------+------+------+--------------------+ | 1 | 2 | 4 | 7 | +------+------+------+--------------------+
SET @pos := 0; #这里用等号,感觉像是逻辑判断,结果也不对了
SELECT @pos:=@pos+1 as rank,name FROM players ORDER BY score DESC;
SET @counter:=0;
SELECT
users.*
FROM
users
HAVING
(@counter:=@counter+1)%100=0
ORDER BY
user_id; |
SELECT @total := COUNT(*) FROM table_name; # simicolon 分割连个语句 SELECT table_name.id COUNT(*) AS ‘count‘, COUNT(*) / (SELECT @total) AS percent FROM table_name, WHERE 1=1 GROUP BY YEAR(birthday) ORDER BY YEAR(birthday)
注意上面这个SQL语句看起来逻辑清晰,但与下面的语句执行效果和时间都一样(可能MySQL内部优化了)
SELECT table_name.id COUNT(*) AS ‘count‘, COUNT(*) / (SELECT
COUNT(*)
FROM
table_name) AS percent
FROM table_name, WHERE 1=1 GROUP BY YEAR(birthday) ORDER BY YEAR(birthday)
其他一些例子:
http://www.mysqldiary.com/user-defined-variables/
疑问:
这里的变量只能保存一个结果值,如何才能临时保存一个select出的结果集呢。
当然简单的方法是创建表/视图; 或者临时表 ,还有好的方法呢? 待研究。
DECLARE @var_name var_type
这里举个例子:
例1:
DECLARE @total INT DECLARE @total_distinct INT SELECT @total:=COUNT(lice_no) #using ":=" notation FROM table_name; SELECT @total_distinct:=COUNT( DISTINCT lice_no) #using ":=" noations FROM table_name; SELECT @total - @total_distinct
例2:
DECLARE @register_count INT; DECLARE @total_count INT; SELECT @register_count := COUNT(1) FROM t1 WHERE id > 10 ;
SELECT @total_count := COUNT(1) FROM t1 ; SELECT (@register_count * @total_count) AS ratio2
- DECLARE 必须指定类型,而SET是不用的
- SET定义的是用户自定义变量,是Session Sensitive 的; DECLARE 声明的变量一般为局部变量,其有效区间是声明的函数或存储过程中。
- 在变量没有用后,可以哦那个SELECT var_name := init_value。 设置为初始值。方便以后用,避免变量值在下一次引用上一次旧指带来的错误。
- 定义全局变量应该为 SET GLOBAL @var_name 后者SET @@GLOBAL.var_name
Mysql User-Defined Variables 用户自定义变量 SET or DECLARE,布布扣,bubuko.com
Mysql User-Defined Variables 用户自定义变量 SET or DECLARE
原文:http://blog.csdn.net/acema/article/details/37114379