2015-10-21 48 views
1

的表中的最新條目列表這類似於我有表:如何以檢索每個「播放器」

+-----------+--------+ 
| Player id | Score | 
+-----------+--------+ 
| User 1 | 10 | 
| User 2 | 22 | 
| User 1 | 17 | 
| User 3 | 34 | 
| User 4 | 23 | 
| User 2 | 12 | 
| User 3 | 10 | 
| User 4 | 30 | 
+-----------+--------+ 

我也有各行的時間戳。

什麼是最好的方式來獲得每個'球員'最近的行。像下面這樣的結果:

+-----------+--------+ 
| Player id | Score | 
+-----------+--------+ 
| User 1 | 10 | 
| User 2 | 22 | 
| User 3 | 34 | 
| User 4 | 23 | 
+-----------+--------+ 

回答

1

嘗試此查詢

SELECT Player_id, 
SUBSTRING_INDEX(GROUP_CONCAT(score ORDER BY date_added DESC),',',1) AS recent_score, 
SUBSTRING_INDEX(GROUP_CONCAT(date_added ORDER BY date_added DESC),',',1) AS recent_date 
    FROM table 
GROUP BY Player_id 

在這裏,我假設你的時間戳字段作爲DATE_ADDED,也可以通過最近的日期得分

+0

請檢查。我編輯了代碼 –

1

我想你可以用這樣一個查詢這個:
time field是你的時間戳字段,詳述最近的記錄)

SELECT 
    `t1`.`Player id`, `t1`.`Score`, `t1`.`time field` 
FROM `yourTable` As `t1` 
    JOIN 
    `yourTable` As `t2` 
    ON `t1`.`Player id` = `t2`.`Player id` 
    AND `t1`.`time field` <= `t2`.`time field` 
GROUP BY 
    `t1`.`Player id`, `t1`.`Score`, `t1`.`time field` 
HAVING 
    COUNT(`t2`.`Player id`) = 1; 

[SQL Fiddle Demo]

0

,我認爲這可以幫助你:

SELECT 
    <Player_id>, <Score> 
FROM 
    <your_table> 
WHERE 
    (<clientID>,<timestamp>) IN (
     SELECT 
      <Player_id>, MAX(<timestamp>) 
     FROM 
      <your_table> 
     GROUP BY 
      <Player_id> 
    ); 

只需更換<enclosed>部分與表的對應的列名。

相關問題