我有一个团队表
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;
它可能很直接,但我似乎无法弄清楚,我如何添加一个&#39;位置&#39;列表示为&#39; POS&#39;在联赛表的最左侧,将显示每个球队在桌面排名,如自动增量?
谢谢! :)
更新:
我已经设法让排名列在联赛表的左侧工作,但它显示了队伍对应的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;
答案 0 :(得分:0)
这是你要找的吗?
SET @rownum := 0;
SELECT @rownum := @rownum + 1 AS rank, <other columns>
FROM <tables >
where ..