0

球员联赛

  • 联赛ID

  • player_id

  • player_position

玩家统计

  • player_id

  • 分数

我有两个表,我想更新 PlayerLeague,设置 player_position 等于行号:

SELECT * FROM PlayerStat s JOIN PlayerLeague l 
ON s.player_id=l.player_id WHERE l.league_id=3 ORDER BY score DESC;

我试图在我的选择中使用@i,但是加入 ORDER BY 被忽略了。

更新

所以,现在我有了这个并且它正在工作,但我不确定这是正常的方式。它将为三个联赛 40-500 名球员每小时运行一次。

SET @i=0;
UPDATE PlayerLeague ll set ll.player_position = ( SELECT position FROM (SELECT
s.player_id, @i:=@i+1 as position
FROM PlayerStat s
where s.player_id in
  (SELECT player_id from PlayerLeague l WHERE l.league_id = 3)
  ORDER BY score DESC) AS t WHERE t.player_id=ll.player_id);
4

2 回答 2

0

认识这个可爱的小怪物:

UPDATE PlayerLeague AS l
    JOIN (
        SELECT p.player_id, @i := @i + 1 AS player_position
        FROM (
            SELECT ss.player_id
            FROM PlayerStat AS ss
                JOIN PlayerLeague AS ll
                    ON ss.player_id=ll.player_id
            WHERE ll.league_id=3
            ORDER BY ss.score DESC
        ) AS p, (SELECT @i := 0) AS tmp
    ) AS s ON s.player_id=l.player_id
SET l.player_position = s.player_position

那么,这里发生了什么?

  • 最内层查询按得分顺序选择联赛中的所有球员。
  • 它包含在添加行数的查询中。
  • 最后,外部 UPDATE 完成您需要的操作:将行数添加到 PlayerLeague 表中。
于 2013-10-06T08:00:15.640 回答
0

尝试

SELECT *
  FROM PlayerStat s
 where s.player_id in
       (select player_id from PlayerLeague l WHERE l.league_id = 3)
 ORDER BY score DESC;
于 2013-10-06T02:14:26.113 回答