mysql - SQL @x := @x +1 和 @x := 0 是什么意思?
问题描述
我在 leetcode 上做排名分数问题,我不确定下面的解决方案。我可以理解除@x := @x +1
和之外的所有部分@x := 0
。
select scores.score, ranks.rank from scores left join (
select score, @x := @x +1 as rank from (select distinct score from scores order by score desc) s, (select @x := 0) r
)
as ranks on scores.score = ranks.score order by scores.score desc;
任何人都可以帮忙吗?
解决方案
声明一个 var@x
初始化它为 int0
select @x := 0
当你做select
子句时,@x
将添加1
.
select @x := @x +1
这是一个示例
架构(MySQL v5.6)
CREATE TABLE T(
col1 varchar(51)
);
INSERT INTO T VALUES ('TEST');
INSERT INTO T VALUES ('TEST1');
查询 #1
SELECT *,@x:=@x +1
FROM T CROSS JOIN (select @x := 0) v;
| col1 | @x := 0 | @x:=@x +1 |
| ----- | ------- | --------- |
| TEST | 0 | 1 |
| TEST1 | 0 | 2 |
笔记
select score, @x := @x +1 as rank
from (select distinct score from scores order by score desc) s, (select @x := 0) r
,
查询中两个表之间的 逗号表示CROSS JOIN
推荐阅读
- aws-codebuild - 如何安装 netfx-4.7.2-devpack 因巧克力而失败
- firebase - 尝试在空对象引用上调用虚拟方法“java.lang.String com.practice.projectbm.Model.User.getName()”
- database - MongoDB $lookup 字段和 $ addedField 作为 foreignField
- google-cloud-platform - Google Cloud Logging:没有使用项目作为资源名称的 LogEntry
- asp.net - 如何从 ReactJS 将数据发布到 ASP.NET Core
- reactjs - 如何键入组件的链接类?
- php - 检查 preg_match_all 的字符串和 guid
- amazon-web-services - 来自 lambda 的身份验证以使用 apikey 调用 AppSync
- swiftui - 如何更改列表区域周围的颜色?
- javascript - 仅在滚动部分后更改背景颜色