gpt4 book ai didi

mysql - 从每个对话中获取最后一条消息

转载 作者:可可西里 更新时间:2023-11-01 06:30:31 25 4
gpt4 key购买 nike

我知道以前有人问过类似的问题,但他们都没有同样的条件,他们的答案不适用于这种情况。

包含消息的表格如下所示:

id | owner_id | recipient_id | content      | created
1 | 1 | 2 | Hello | 2015-12-08 20:00
2 | 2 | 1 | Hey | 2015-12-08 20:10
3 | 3 | 1 | You there? | 2015-12-08 21:00
4 | 1 | 3 | Yes | 2015-12-08 21:15
5 | 4 | 1 | Hey buddy | 2015-12-08 22:00

假设我从用户 ID 1 的每个对话中查询最后一条消息,预期结果是:

id | owner_id | recipient_id | content      | created
5 | 4 | 1 | Hey buddy | 2015-12-08 22:00
4 | 1 | 3 | Yes | 2015-12-08 21:15
2 | 2 | 1 | Hey | 2015-12-08 20:10

我尝试了很多组合,使用 JOIN 和子查询,但没有一个给出预期的结果。

这是我尝试过的查询之一,但它不起作用。我相信这甚至不符合我的需要。

SELECT
IF ( owner_id = 1, recipient_id, owner_id ) AS Recipient,

(
SELECT
content
FROM
messages

WHERE
( owner_id = 1 AND recipient_id = Recipient )
OR
( owner_id = Recipient AND recipient_id = 1 )

ORDER BY
created DESC

LIMIT 1
)
FROM
messages

WHERE
owner_id = 1
OR
recipient_id = 1

GROUP BY
Recipient;

最佳答案

select t.* 
from
t
join
(select user, max(created) m
from
(
(select id, recipient_id user, created
from t
where owner_id=1 )
union
(select id, owner_id user, created
from t
where recipient_id=1)
) t1
group by user) t2
on ((owner_id=1 and recipient_id=user) or
(owner_id=user and recipient_id=1)) and
(created = m)
order by created desc

example on sqlfiddle

关于mysql - 从每个对话中获取最后一条消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34342835/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com