2013-10-06 72 views
0

PlayerLeagueMySQL的選擇數

  • 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被忽略。

UPDATE

所以,現在我也這樣與它的工作,但我不知道它的正常方式。 它將每小時運行三個聯賽40-500名球員。

SET @i=0; 
UPDATE PlayerLeague ll set ll.player_position = (SELECT position FROM (SELECT 
s.player_id, @i:[email protected]+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); 
+0

「但與連接ORDER BY被忽略。」 ---它不被忽略。 'ORDER BY'按你傳遞給它的任何表達式或列來排序 – zerkms

+0

你有多少行l.league_id = 3? – Mihai

+0

Mihai,我有3個聯賽,從40到500個球員 –

回答

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表中。
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; 
+0

ty。我用你的代碼更新了帖子。 –