这段只是工作遇到的问题,只给自己做个记录
一 、
– set @a=‘test’:
– select @a,(@a:=20) from auser; # 第一个@a 是取值的上一行的值 ,第二个@a 是取的当时自定义的值
– select * from auser; # 但是再查询 @ 时候 就不包含@a 这个变量了,也就是@a 这个变量是不是就是临时的??
select *,(@c:=@c+2) as cc from auser,(select @c:=1)s; – 先执行from后面的再执行前面的
#第一列不是动态的 只有第二列是动态的,并且是随着每列来逐步增加的
select 前面的 @c + 2 是 在 后面的from 中的 @c:=1 的基础上得来的
select * from auser; – @b的默认值是Null
mysql 关于用户定义变量@ : ------
二 、
– select a.s_id,a.c_id,
– @i:=@i +1 as i保留排名,
– @k:=(case when @score=a.s_score then @k else @i end) as rank不保留排名,
– @score:=a.s_score as score
– from (
– select s_id,c_id,s_score from Score GROUP BY s_id,c_id,s_score ORDER BY s_score DESC
– )a,(select @k:=0,@i:=0,@score:=0)s;
– select a.s_id,a.c_id,
– @i:=@i+1 as i保留排名,
– @k:=(case when @score=a.s_score then @k else @i end) as rank保留排名,
- @score:=a.s_score
–
– from (select * from Score order by s_score desc)a,(select @i:=0,@k:=0,@score:=0)s;
– select ,
– @i:=@i +1 as i保留排名,
– @k:=(case when @score=a.s_score then @k else @i end) as rank不保留排名,
– @score:=a.s_score as score
– from (
– select s_id,c_id,s_score from Score GROUP BY s_id,c_id,s_score ORDER BY s_score DESC
– )a,(select @k:=0,@i:=0,@score:=0)s;
#从头至尾,select 后边的 @ 表达式形成的变量都不包括在真正的表里
– 设置的用户变量的初始值是 @k @i @score
上面sql语句的执行顺序是: 先执行 from 后边的,如果 select * 中有包含 @ 变量,那么 @ 变量还是保持和from 后边设置的@变量的值一致,
如果 select 里边含有 @变量 的一个算术表达式,那么此表达式是根据前一个@ 变量的表达式而来的,也就是在原有的@ 表达式的基础上进行计算,这道题里最开始是根据 from 后边的@ 表达式的
基础上进行计算
其实@ 用户定义变量的本质就是在原有表格的基础上做标记,相当于一个透视表,但是它又不会对原有表格改变任何。
#关于 @ 用户定义变量 -------
– select s_id,c_id,s_score,count() from Score GROUP BY s_id,c_id,s_score ORDER BY s_score DESC; # 18 # count() 那一列是1
– select count() from Score; # 查询所有记录的条数----
– select s_id,c_id,s_score from Score GROUP BY s_id,c_id,s_score ORDER BY s_score DESC; # 18
– select * from Score order by s_score desc; #18 这个结果的顺序 和 上面的语句的结果的顺序是一样的
– select * from Score;
– select * from Score group by s_id,c_id,s_score; # 18行 并且和原表的顺序保持不变
– (select * from (select
– t1.c_id,
– t1.s_score, #下面括号里边的这个数字代表自己的排名 # 有多少大于当前的分数,代表当前的这个数字是排名第几,这个排名的关键是这个
– (select count(distinct t2.s_score) from Score t2 where t2.s_score>=t1.s_score and t2.c_id=‘01’) rank
– FROM Score t1 where t1.c_id=‘01’
– order by t1.s_score desc) t1);
– select t1.c_id, t1.s_score from Score t1 where c_id=‘01’ order by t1.s_score desc;
– select a.c_id, a.s_score,(
– select count(*) from Score b where b.s_score>=75) # 这个运算在每行都做;
– from Score a ;
– 来不及整理 只有自己看的懂吧 等有时间了再整理
– 19、按各科成绩进行排序,并显示排名