sql@x:=@x+1和@x:=0是什么意思?

wrrgggsh  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(344)

我在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;

有人能帮忙吗?

hs1rzwqc

hs1rzwqc1#

声明变量 @x 初始化为int 0 ```
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
TEST01
TEST102
db fiddle视图
笔记

select score, @x := @x +1 as rank
from (select distinct score from scores order by score desc) s, (select @x := 0) r

这个 `,` 查询中两个表之间的逗号表示 `CROSS JOIN` 

相关问题