2013-03-29 90 views
0

在下表中,我不確定如何執行此操作,但我該如何着手編寫查詢,該查詢返回每個唯一PhoneNumber的最新行?MySQL:如何返回每個唯一編號的最近一行

PhoneNumber MessageText    ReceiveTime   
------------- ------------------------ ------------------- 
+639148186649 Delivery please   2013-03-19 01:12:55 
+639148186649 I need this item   2013-03-22 02:15:01 
+639148186649 I need more of this item 2013-03-23 12:01:02 
+639194357455 How much for this...  2013-03-24 16:36:33 
+639194357455 What time do you open? 2013-03-24 17:55:07 

回答

0

您無法按一列分組並返回不依賴於該組的其他列。有關提示,請參閱this question的答案。

0

我認爲這應該工作...

SELECT * 
FROM PhoneTable 
GROUP BY PhoneNumber 
HAVING ReceiveTime = MAX(ReceiveTime) 
ORDER BY ReceiveTime 

..或者你可能不得不做這樣的事情......

SELECT PhoneNumber, MessageText, ReceiveTime 
FROM PhoneTable t 
WHERE ReceiveTime = (SELECT MAX(ReceiveTime) 
        FROM t 
        GROUP BY PhoneNumber 
        HAVING PhoneNumber = t.PhoneNumber) 
+0

不應該鼓勵使用'GROUP BY'。 – Kermit

+0

這兩個錯誤。 '錯誤代碼:1242 子查詢返回多於一行' – enchance

1

我找到了答案!

SELECT s1.PhoneNumber, s1.MessageText, s1.ReceiveTime FROM mytable s1 LEFT JOIN mytable s2 
    ON (s1.PhoneNumber = s2.PhoneNumber AND s1.ReceiveTime < s2.ReceiveTime) 
    WHERE s2.ReceiveTime IS NULL ORDER BY ReceiveTime DESC 
相關問題