首页 > 解决方案 > 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;

任何人都可以帮忙吗?

标签: mysqlsql

解决方案


声明一个 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         |

在 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

推荐阅读