简单的mysql语句MySql查询语句中的变量使⽤
前⾔
今⽇在LeetCode刷MySql的题,遇到⼀题,题⽬倒没什么,解答完了之后习惯去看此题的题解,有位⼤佬的思路让博主感觉很惊艳,⾄此,特地记录学习⼀下。
题⽬
解答
乍⼀看题⽬也没啥,分数排名,思路是⾸先获取每个分数对应的排名,使⽤变量实现排名顺序,⽣成⼀张临时表,最后⽤主表关联临时表按主表分数倒序得到每条分数的排名,可能⼤部分童鞋都是跟博主⼀样的思路,实现代码如下
SELECT
s.Score,
s1.`Rank`
FROM
Scores s,
(
SELECT
@rownum :=@rownum+1AS `Rank`,
t.Score
FROM
(SELECT@rownum :=0) r,
(
SELECT
Score
FROM
Scores
GROUP BY
Score
ORDER BY
Score DESC
) t
) s1
WHERE
s.Score = s1.Score
ORDER BY
s.Score DESC
结果也是正确的,于是提交完了之后去看看题解,学习下别⼈的思路,该⼤佬提供的题解如下,顿时就觉得妙啊,代码并不难,都能看得懂,但是却想不到,这条sql写出了for循环代码的感觉,这种思维真是值得学习
在这格式化⼀下⼤佬的sql
SELECT
Score,
Rank
FROM
(
SELECT
Score,
@curRank :=IF (@prevRank= Score,@curRank+0 ,@curRank :=@curRank+1) AS Rank,
@prevRank := Score
FROM
Scores,
(
SELECT
@curRank :=0,
@prevRank :=NULL
) r
ORDER BY
Score DESC
) s
后续
认真阅读完题解之后,博主继续刷题。。。⼜遇到⼀题,若是在以前,肯定⼀时半会想不出来,想出来了也会复杂的⼀批。可刚刚看完了题解之后,看到这题⽴马就有了新的思路,于是学以致⽤,概念⼀套,轻松解决~  该题如下
解答sql
SELECT
DISTINCT tt.Num AS ConsecutiveNums
FROM
(
SELECT
t.*,
@times :=IF ( @before_num= t.Num ,@times+1, 1 ) AS times,
@before_num := t.Num
FROM
(SELECT@times :=1 ,@before_num :=NULL) r,
LOGS t
) tt
WHERE
tt.times >=3
后后续
次⽇刷题⼜遇到⼀题,看到此题习惯性的⼜想到⽤变量解决
思路是给每条记录⼀个flag,当连续符合>=100条件时,此flag则是⼀样的,最后根据flag分组,筛选出>=3条的记录,得到每组的maxId和minId,最后再关联stadium表,根据maxId和minId两个条件,得到正确的结果
解答sql
SELECT
s2.id,
s2.visit_date,
s2.people
FROM
(
SELECT
max(id) maxId,min(id) minId
FROM
(
SELECT
@flag :=IF (t.people >=100AND@bfr>=100 ,@flag,@flag+1) AS flag,
@bfr := t.people AS bfr,
t.id,
t.visit_date,
t.people
FROM
(SELECT@flag :=0 ,@bfr :=NULL) r,
stadium t
) t
GROUP BY t.flag
HAVING count(1) >=3
) s1,
stadium s2
WHERE
s2.id <= s1.maxId
and s2.id >= s1.minId
order by s2.id

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。