mysql选择行数

时间:2013-10-06 02:06:06

标签: mysql sql select

PlayerLeague

  • league_id

  • player_id

  • player_position

PlayerStat

  • 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);

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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表中。