从内部联接记录中选择最后一条记录

时间:2015-11-19 14:15:52

标签: mysql sql mysqli

我6天前发了一个帖子,但似乎没有人正确地回答它最终被放弃了所以我在这里再次发布(抱歉DPing,但这对我来说很重要) 我有2个表 - 人(查询基于people.id所以不需要整个表)和消息(http://prntscr.com/94iq2e

我有一个查询,它将消息与人分组,并且工作正常,但每个人都与他发送的第一条消息分组,我需要进行分组,以便人们使用他们发送的最后消息对人进行分组

以下是使用FIRST消息对人进行分组的查询

SELECT     people.id, 
       people.avatar, 
       people.firstname, 
       people.lastname, 
       LEFT(messages.message, 90) AS message, 
       messages.seen, 
       messages.date 
FROM       people 
INNER JOIN messages 
ON         people.id = messages.sender_id 
WHERE      reciever_id = '". $user_data['id'] ."' 
GROUP BY   sender_id 
ORDER BY   date DESC limit 11

链接到上一主题 - > Selecting last record from INNER JOIN and grouping

3 个答案:

答案 0 :(得分:1)

您可以使用返回最大日期的子查询:

SELECT sender_id, MAX(date) AS max_date
FROM messages
GROUP BY sender_id

并使用此子查询加入人员表,然后加入到消息表以获取具有最大日期的消息:

SELECT
   people.id, 
   people.avatar, 
   people.firstname, 
   people.lastname, 
   LEFT(messages.message, 90) AS message, 
   messages.seen, 
   messages.date 
FROM
   people INNER JOIN (
     SELECT sender_id, MAX(date) AS max_date
     FROM messages
     GROUP BY sender_id
   ) lm ON people.id = lm.sender_id
   INNER JOIN messages 
   ON people.id = messages.sender_id AND
      lm.max_date=messages.date
WHERE
   reciever_id = ...
ORDER BY
   ...

答案 1 :(得分:0)

我建议使用子查询来提取最新消息。以下链接可能对您有所帮助,它详细介绍了一些可能的解决方案。

SQL join: selecting the last records in a one-to-many relationship

干杯, 鲍勃

答案 2 :(得分:0)

我不知道mysql,但在TSQL中,这样可以得到最后一条消息:

ISNULL(SELECT TOP 1 messages.message FROM messages WHERE people.id = messages.sender_id ORDER BY messages.id DESC,'')

整个代码看起来像这样:

 SELECT     people.id, 
   people.avatar, 
   people.firstname, 
   people.lastname, 
   ISNULL(SELECT TOP 1 messages.message FROM messages WHERE people.id = messages.sender_id ORDER BY messages.id DESC,'') AS message, 
   messages.seen, 
   messages.date 
FROM       people 
INNER JOIN messages 
ON         people.id = messages.sender_id 
WHERE      reciever_id = '". $user_data['id'] ."' 
GROUP BY   sender_id 
ORDER BY   date DESC limit 11