[英]MySQL get last message for each conversation
我对 mysql 有很大的问题,因为我是前端开发人员,而且我对 SQL 很差 ^^
我在数据库 + 用户表中有 3 个表
参与者:
+----+---------+-----------------+---------------------+
| id | user_id | conversation_id | updated_at |
+----+---------+-----------------+---------------------+
| 1 | 1 | 1 | 2022-01-03 00:00:00 |
| 2 | 2 | 1 | 2022-01-03 00:00:00 |
| 3 | 1 | 2 | 2022-01-03 00:00:00 |
| 4 | 3 | 2 | 2022-01-03 00:00:00 |
| 5 | 1 | 2 | 2022-01-03 00:00:00 |
+----+---------+-----------------+---------------------+
对话:
+----+---------------------+
| id | updated_at |
+----+---------------------+
| 1 | 2022-01-03 00:00:00 |
| 2 | 2022-01-03 00:00:00 |
+----+---------------------+
留言:
+----+----------------+-----------------+-------------------+----------------------+
| id | participant_id | conversation_id | message | updated_at |
+----+----------------+-----------------+-------------------+----------------------+
| 1 | 1 | 1 | test msg 1 room 1 | 2022-01-03 00:00:00 |
| 1 | 1 | 1 | test msg 2 room 1 | 2022-01-05 00:00:00 |
| 1 | 2 | 1 | test msg 3 room 1 | 2022-01-07 00:00:00 |
| 1 | 3 | 2 | test msg 1 room 2 | 2022-01-03 00:00:00 |
| 1 | 2 | 2 | test msg 2 room 2 | 2022-01-04 00:00:00 |
| 1 | 1 | 2 | test msg 3 room 2 | 2022-01-05 00:00:00 |
| 1 | 1 | 1 | test msg 4 room 1 | 2022-01-14 00:00:00 |
+----+----------------+-----------------+-------------------+----------------------+
所以我试图从每个房间获取最后一条消息,但我有问题,当我尝试分组时,我有这样的错误
错误代码:1055。SELECT 列表的表达式 #1 不在 GROUP BY 子句中,并且包含在功能上不依赖于 GROUP BY 子句中的列的非聚合列“zzzz”; 这与 sql_mode=only_full_group_by 不兼容
有可能得到每个房间的最后一条消息吗? 像这样
+-----------------+-------------------+----------------------+
| conversation_id | message | updated_at |
+-----------------+-------------------+----------------------+
| 2 | test msg 3 room 2 | 2022-01-05 00:00:00 |
| 1 | test msg 4 room 1 | 2022-01-14 00:00:00 |
我尝试过这样的事情,但没有工作......
WITH RECURSIVE test AS (
SELECT
pp.user_id,
pp.conversation_id,
pp.updated_at
FROM
participants pp
UNION
SELECT
p.user_id,
p.conversation_id,
p.updated_at
FROM
participants p
INNER JOIN conversations c ON c.id = p.conversation_id
) SELECT
m.conversation_id,
m.message,
m.updated_at
FROM
test t
INNER JOIN messages as m ON m.conversation_id = t.conversation_id
ORDER BY m.updated_at DESC
;
如果我正确理解你的问题。 您需要的一切都可以来自消息表。 所以你可以尝试这样的事情:
WITH cte as(
SELECT
RIGHT (message,LENGTH(message)-LOCATE('r',message)) AS room,
MAX(LEFT (message,LENGTH(message)-LOCATE('m',message))) AS msg,
MAX(updated_at) AS updated_at
FROM messages
group by room
)
select *
FROM messages
WHERE RIGHT (message,LENGTH(message)-LOCATE('r',message)) in (select room from cte)
AND LEFT (message,LENGTH(message)-LOCATE('m',message)) in (select msg from cte)
AND updated_at in (select updated_at from cte)
如果我误解了什么,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.