=>我想基于创建日期字段获取两个用户之间的聊天转换的最新记录,以获取最新消息。下面是我的桌子
我尝试使用此查询来获取聊天转换的最后一条消息的结果,但我无法获得正确的结果。
select `chat_messages`.`id`, `chat_messages`.`message`, `chat_messages`.`created_at`
from `chat_messages`
where `chat_messages`.`is_group` = 0
and `chat_messages`.`deleted_at` is null
and (`sender_id` =141 or `client_id` = 141)
group by `chat_messages`.`message_token`
order by `chat_messages`.`created_at` desc
=>当前结果:-
=>应该是:-
注意:-此功能类似于聊天功能,我不想只获得一条记录。
谢谢。
答案 0 :(得分:1)
group by
导致了您的问题。您需要做的是对desc排序,然后将结果集限制为一行
select `chat_messages`.`id`, `chat_messages`.`message`, `chat_messages`.`created_at`
from `chat_messages`
where `chat_messages`.`is_group` = 0
and `chat_messages`.`deleted_at` is null
and (`sender_id` =141 or `client_id` = 141)
order by `chat_messages`.`created_at` desc
LIMIT 1
答案 1 :(得分:1)
为什么要按message_token
分组?
我认为此查询将是有效的:
select `chat_messages`.`id`, `chat_messages`.`message`, `chat_messages`.`created_at`
from `chat_messages`
where `chat_messages`.`message_token` = '144_141'
and `chat_messages`.`is_group` = 0
and `chat_messages`.`deleted_at` is null
order by `chat_messages`.`created_at` desc
limit 1
编辑后:
select `chat_messages`.`id`, `chat_messages`.`message`, `chat_messages`.`created_at`
from (select * from `chat_messages` order by `chat_messages`.`created_at` desc) as chat_messages
where `chat_messages`.`is_group` = 0
and `chat_messages`.`deleted_at` is null
and (`sender_id` =141 or `client_id` = 141)
group by `chat_messages`.`message_token`;
答案 2 :(得分:1)
如果您按message_token分组,那么您将加入所有这些消息,则必须在where语句中选择该消息行,其中message_token = XXX。
SELECT
`chat_messages`.`id`,
`chat_messages`.`message`,
`chat_messages`.`created_at`
FROM
`chat_messages`
WHERE
`chat_messages`.`is_group` = 0
and `chat_messages`.`deleted_at` is null
and (`sender_id` =141 or `client_id` = 141)
and `chat_messages`.`message_token`= "146_141"
ORDER BY
`chat_messages`.`created_at` desc,
`chat_messages`.`id` desc
答案 3 :(得分:0)
我假设您具有消息模型(您正在使用laravel)
下面的查询应该给您您想要的东西。
Message::whereSenderIdAndClientId($userId1,$userId2)
->orWhere([
["sender_id", $userId2],
["client_id",$userId1]
])
->orderBy("created_at","desc")
->first()
获取发件人和客户端之间的消息,然后按created_at-desc的顺序对消息进行排序,然后采用第一个消息,即彼此之间的最后一条消息。