2011-05-09 210 views
3

我不知道如何編寫獲取最後一條記錄的SQL語法(根據最近的帖子,沒有回覆)。獲取每個記錄組的最後一條記錄

我的表

+-------------------+-----------------------+------+-----+---------+----------------+ 
| Field    | Type     | Null | Key | Default | Extra   | 
+-------------------+-----------------------+------+-----+---------+----------------+ 
| notification_id | mediumint(8) unsigned | NO | PRI | NULL | auto_increment | 
| user_id   | mediumint(8) unsigned | NO |  | NULL |    | 
| notification_msg | text     | NO |  | NULL |    | 
| notification_date | int(11) unsigned  | NO |  | NULL |    | 
| private_message | tinyint(1) unsigned | NO |  | 0  |    | 
| has_replied  | tinyint(1) unsigned | NO |  | 0  |    | 
| reply_id   | mediumint(8) unsigned | NO |  | 0  |    | 
+-------------------+-----------------------+------+-----+---------+----------------+ 

基本上每個線程的通知,它應該得到每個通知記錄中的最後一條記錄,並檢查是否has_replied0,如果是0,那麼它應該返回它使PHP可以讀取是否有沒有回覆的通知。因此,它應該像這樣返回(僞):

+--------------+-----+-----+ 
| username  | 1 | 4 | 
| username2 | 0 | 2 | 
+--------------+-----+-----+ 

其中第二列表示是否回覆上一篇文章。

我現在的SQL語法(的作品,但沒有得到最後的記錄,如果它回答):

SELECT n.*, 
     m.user_id, 
     m.username 
FROM notifications n 
INNER JOIN members m ON n.user_id = m.user_id 
WHERE private_message = 1 
AND reply_id = 0 
ORDER BY has_replied ASC, 
     notification_date DESC 
+2

+1。我喜歡桌子格式':)' – 2011-05-09 20:39:24

+0

很高興你喜歡它。 – MacMac 2011-05-09 20:39:55

+0

僞輸出中的第三列是什麼? – 2011-05-09 20:47:03

回答

1
Select m.user_id, m.username 
    , N... 
From members As M 
    Join (
      Select user_id, Max(notification_id) As notification_id 
      From notifications 
      Group By user_id 
      ) As UserLastNotification 
     On UserLastNotification.user_id = m.user_id 
    Join notifications As N 
     On N.notification_id = UserLastNotification.notification_id 
Where N.private_message = 1 
    And N.reply_id = 0 
Order By N.has_replied, N.notification_date Desc 

請注意,這將過濾每個用戶的最後通知是一條私人消息,並且reply_id爲零。

+0

假設你認爲'LEFT OUTER JOIN'或'INNER JOIN'會比'JOIN'好?如我錯了請糾正我。 – MacMac 2011-05-09 21:04:27

+0

@lolwut - 'Join'是'Inner Join'的縮寫。同樣,「左連接」是「左外連接」的縮寫。但是,是否使用左連接與內連接取決於您正在嘗試完成的工作。如果你想要所有成員是否有通知,那麼我需要將Where子句中的條件移動到UserLastNotification的On子句中。 – Thomas 2011-05-09 21:09:29

+0

沒關係。都很好。謝謝。 :-) – MacMac 2011-05-09 21:12:08

0

簡單

LIMIT 1 

在查詢到底應該足以只返回最後一篇文章。

相關問題