2014-01-22 15 views
1

我試圖用表格中的條目構建高分表在mysql中:如果兩個值相等(如果兩個值相等時應如何選擇最近添加的行)(應用程序是遊戲高分表)

id(int) | username(varchar) | score(int) | modified (timestamp) 

選擇每天的得分最高爲每個用戶工作良好使用下列內容:

SELECT id, username, MAX(score) AS hiscore 
FROM entries WHERE DATE(modified) = CURDATE() 

我在哪裏卡住的是,在某些情況下起着多次就可以達到同樣的比分在同一天,在這種情況下,我需要確保它始終是最早的一個因爲2分的比賽而被選中的人將成爲第一個獲得該分數的人。

如果我的表包含以下內容:

id |  username  | score |  modified 
________|___________________|____________|_____________________ 
    1 |  userA   |  22 | 2014-01-22 08:00:14 
    2 |  userB   |  22 | 2014-01-22 12:26:06 
    3 |  userA   |  22 | 2014-01-22 16:13:22 
    4 |  userB   |  15 | 2014-01-22 18:49:01 

在這種情況下返回的中獎表應該是:

id |  username  | score |  modified 
________|___________________|____________|_____________________ 
    1 |  userA   |  22 | 2014-01-22 08:00:14 
    2 |  userB   |  22 | 2014-01-22 12:26:06 

我試圖通過增加ORDER BY modified desc到查詢來實現這一點,但它總是返回後面的分數。我也試過ORDER BY modified asc,但是我得到了相同的結果

回答

3

這是經典的問題,它在StackOverflow上經常被回答。下面是你的情況的解決方案:

SELECT e.* 
FROM entries e 
JOIN (
    SELECT DATE(modified) AS modified_date, MAX(score) AS score 
    FROM entries 
    GROUP BY modified_date 
) t ON DATE(e.modified) = t.modified_date AND e.score = t.score 
WHERE DATE(e.modified) = CURDATE() 
+0

好了,我的想法,儘管使用這個語句是SQL的錯誤結果:未知列「e.modified_date」在'where子句' – Finglish

+0

我的錯誤。我已糾正它。 –

0

我認爲這會爲你的作品,是最簡單的方法:

SELECT username, MAX(score), MIN(modified) 
FROM entries 
GROUP BY username 

這將返回該你的情況:

"userB";22;"2014-01-22 12:26:06" 
"userA";22;"2014-01-22 08:00:14" 

然而,我認爲你想要的(在你的例子中是錯的)最近的一行。要做到這一點,你需要這樣的:

SELECT username, MAX(score), MAX(modified) 
FROM entries 
GROUP BY username 

將返回:

"userB";22;"2014-01-22 18:49:01" 
"userA";22;"2014-01-22 16:13:22" 
相關問題