gpt4 book ai didi

mysql - 如何编写查询以从 SQLite/MySQL 检索最后更新的行?

转载 作者:太空宇宙 更新时间:2023-11-03 11:05:17 25 4
gpt4 key购买 nike

我有一张 table 聊天
列是 "id"、"sender"、"message"、"time"、"sender_email"。插入到 chat 中的一些聊天记录,例如:

1 John hihi 10:45 john@email.com
2 John hihi 10:46 john@email.com
3 Peter hihi 10:47 peter@email.com
4 John hihi 10:48 john@email.com
5 John hihi 10:49 john@email.com
6 John hihi 10:50 john@email.com
7 Mary hihi 10:51 mary@email.com
8 John hihi 10:52 john@email.com
9 Peter hihi 10:53 peter@email.com
10 John hihi 10:54 john@email.com

我想收到出现在表格中的人的最后一条消息。
如果有人多次出现在表格中,就得到他的最后一条消息。
所以我想得到的结果应该是:

10 John hihi 10:54 john@email.com
9 Peter hihi 10:53 peter@email.com
7 Mary hihi 10:51 mary@email.com

这样可以吗??
到目前为止,我只是写了一个sql:

SELECT DISTINCT name from chat ORDER BY id DESC

但是好像不能显示我想要的。

最佳答案

您必须确定哪些消息是每个用户的最后一条消息(我按 time 执行此操作,但如果您知道更高的值肯定等于稍后的消息),然后获取该消息的数据:

SELECT chat.*
FROM chat
INNER JOIN
(
SELECT MAX(time) AS time, sender
FROM chat
GROUP BY sender
) lastMsg ON chat.time = lastMsg.time AND chat.sender = lastMsg.sender

这还假设 time 没有关系。如果这是可能的,你将不得不通过 id 来代替:

SELECT chat.*
FROM chat
INNER JOIN
(
SELECT MAX(id) AS id
FROM chat
GROUP BY sender
) lastMsg ON chat.id = lastMsg.id

关于mysql - 如何编写查询以从 SQLite/MySQL 检索最后更新的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12345482/

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