如何在sql查询中添加固定位置列?

lnvxswe2  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(415)

我有一张table

CREATE TABLE teams(id int primary key auto_increment,tname char(32) unique);

我还有一张游戏桌

CREATE TABLE games(id int primary key auto_increment, date datetime,
               hteam int, ateam int, hscore tinyint,ascore tinyint);

这是一个显示联赛排名的sql查询

SELECT
tname AS Team, Sum(P) AS P,Sum(W) AS W,Sum(D) AS D,Sum(L) AS L,
SUM(F) as F,SUM(A) AS A,SUM(GD) AS GD,SUM(Pts) AS Pts
FROM(
SELECT
hteam Team,
1 P,
IF(hscore > ascore,1,0) W,
IF(hscore = ascore,1,0) D,
IF(hscore < ascore,1,0) L,
hscore F,
ascore A,
hscore-ascore GD,
CASE WHEN hscore > ascore THEN 3 WHEN hscore = ascore THEN 1 ELSE 0 END PTS
FROM games
UNION ALL
SELECT
ateam,
1,
IF(hscore < ascore,1,0),
IF(hscore = ascore,1,0),
IF(hscore > ascore,1,0),
ascore,
hscore,
ascore-hscore GD,
CASE WHEN hscore < ascore THEN 3 WHEN hscore = ascore THEN 1 ELSE 0 END
FROM games
) as tot
JOIN teams t ON tot.Team=t.id
GROUP BY Team
ORDER BY SUM(Pts) DESC, SUM(GD) DESC, SUM(F) DESC;

这可能是直截了当的,但我似乎不明白,我如何添加一个'位置'列表示为'位置'在最左边的联赛表,将显示每个球队的排名表内,像一个自动递增?
谢谢!:)
更新:
我已经设法得到了一个排名列沿左侧的联赛表,但它显示了球队相应的id,而不是他们的排名在联赛表。

SET @rownum := 0;
SELECT @rownum := @rownum + 1 AS rank, tname AS Team, Sum(P) AS P,Sum(W) AS 
W,Sum(D) AS D,Sum(L) AS L,
SUM(F) as F,SUM(A) AS A,SUM(GD) AS GD,SUM(Pts) AS Pts
FROM(
SELECT
hteam Team,
1 P,
IF(hscore > ascore,1,0) W,
IF(hscore = ascore,1,0) D,
IF(hscore < ascore,1,0) L,
hscore F,
ascore A,
hscore-ascore GD,
CASE WHEN hscore > ascore THEN 3 WHEN hscore = ascore THEN 1 ELSE 0 END PTS
FROM games
UNION ALL
SELECT
ateam,
1,
IF(hscore < ascore,1,0),
IF(hscore = ascore,1,0),
IF(hscore > ascore,1,0),
ascore,
hscore,
ascore-hscore GD,
CASE WHEN hscore < ascore THEN 3 WHEN hscore = ascore THEN 1 ELSE 0 END
FROM games
) as tot
JOIN teams t ON tot.Team=t.id
GROUP BY Team
ORDER BY SUM(Pts) DESC, SUM(GD) DESC, SUM(F) DESC;
bvk5enib

bvk5enib1#

这就是你要找的吗?

SET @rownum := 0;
SELECT @rownum := @rownum + 1 AS rank, <other columns>
FROM <tables >
where ..

相关问题