sql查询以获取最新发送的消息

时间:2019-09-03 18:34:36

标签: mysql sql

我有一个聊天sql表,其结构如下:

DROP TABLE IF EXISTS `chat`;
CREATE TABLE IF NOT EXISTS `chat` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `message` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `idsender` int(11) DEFAULT NULL,
  `sentTime` datetime NOT NULL,
  `idreceiver` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
)

如何从与之交谈的每个用户(其中​​idreceiver = 2)中获取ID为2的最新消息?

这是我的尝试,它向每个ID = 2的用户交谈过的用户发送一条消息,但这不是最后一条消息:

SELECT * FROM chat 
WHERE idreceiver = 2 
GROUP BY idsender 
ORDER BY sentTime DESC

2 个答案:

答案 0 :(得分:0)

不存在:

SELECT c.* FROM chat c 
WHERE c.idreceiver = 2
AND NOT EXISTS (
  SELECT 1 FROM chat
  WHERE idreceiver = c.idreceiver AND idsender = c.idsender AND sentTime > c.sentTime
) 

或者group by idsender并加入表格:

SELECT c.* 
FROM chat c INNER JOIN (
  SELECT idsender, MAX(sentTime) sentTime 
  FROM chat
  WHERE idreceiver = 2
  GROUP BY idsender 
) t ON t.idsender = c.idsender AND t.sentTime = c.sentTime 
WHERE c.idreceiver = 2

答案 1 :(得分:0)

尝试使用此查询:

19.03.1