sql查询/基于两种不同条件获取最新条目

时间:2017-02-15 22:59:01

标签: mysql join

这是我的表结构:

[id] [senderid] [recipientid] [message] [datetime]

我希望获得每个对话的最新条目(基于日期时间)(对于特定用户),结果应为(对于自己的用户ID 1):

435 | 1 | 67 | how are u? | timestampnow

下一个结果(回复后):

436 | 67 | 1 | fine thanks | timestamplater

混淆了如何正确进行查询/连接。我尝试了一些想法:

SELECT * FROM messages MSG

INNER JOIN 
(SELECT MAX(id) MAXDATE,recipientid,senderid 
 FROM messages
 GROUP BY recipientid,senderid) MSG2

ON MSG.recipientid = MSG2.recipientid
AND MSG.id = MAXDATE 

3 个答案:

答案 0 :(得分:0)

Firts使用以下条件构建查询:

SELECT recipientid, MAX(date) mdate
FROM yourTable
GROUP BY recipientid

将其用作子查询:

SELECT a.[id], a.[senderid], a.[recipientid], a.[message], a.[datetime]
FROM yourTable a
    INNER JOIN (SELECT recipientid, MAX(date) mdate
                FROM yourTable
                GROUP BY recipientid) b ON b.recipientid = a.recipientid
                                        AND a.datetime = b.mdate;

答案 1 :(得分:0)

你不需要那里的子选择

可能就是这么简单:

SELECT id, senderid, recipientid, message, MAX(datetime) as datetime
FROM yourTable
GROUP BY recipientid;

答案 2 :(得分:0)

select m.*
from (
    select max(id) as id from (
        select max(id) as id, recipientid as user_id
        from messages
        where senderid = ?
        group by recipientid
        union all
        select max(id) as id, senderid as user_id
        from messages 
        where recipientid = ?
        group by senderid
    ) sub
    group by user_id
) sub
join messages m using(id)

最里面的子查询将返回每个对话最多两个id个(来自上次发送的消息的id和来自上次收到的消息的id。外子查询将获取两个id中最高的一个。然后结果与messages表连接以返回相应的行。

(将?替换为给定的用户ID)

更简短的方法可能是:

select m.*
from (
    select max(id) as id
    from messages
    where ? in (senderid, recipientid)
    group by case when senderid = ? then recipientid else senderid end
) sub
join messages m using(id)

但那个可能会慢一些。