[英]SQL / Laravel: Is it possible to return a deduped results based on two column values?
I have a fairly standard Chat model, which contains messages. 我有一个相当标准的聊天模型,其中包含消息。 For simplicity sake, let's say it has three columns: to_user_id
, from_user_id
and message
. 为了简单起见,假设它具有三列: to_user_id
, from_user_id
和message
。
I want to return a deduped results based on the two column values: to_user_id
and from_user_id
. 我想返回基于两个列值的重复数据删除结果: to_user_id
和from_user_id
。 This is a some I can list the ongoing conversations. 我可以列出正在进行的对话。 I can return a return a deduped set of results using one column value. 我可以使用一个列值返回一个已删除重复数据的结果集。 However, this essential comes back like the below. 但是,此基本要素如下所示。 Obviously, this is because the user can be both the to_user_id
and from_user_id
depending on whether they sent or received the message. 显然,这是因为用户可以同时使用to_user_id
和from_user_id
具体取决于他们是发送还是接收消息。
Tom > Harry 汤姆>哈里
Harry > Tom 哈里>汤姆
John > Chris 约翰>克里斯
Chris > John 克里斯>约翰
I am hoping to get is something like the below, so it groupBy 我希望得到类似下面的东西,所以它
Tom > Harry 汤姆>哈里
John > Chris 约翰>克里斯
Conversations are one-to-one, so will only ever have two participants. 对话是一对一的,因此只有两个参与者。
Any help would be greatly appreciated! 任何帮助将不胜感激!
Not the best solution, but I suppose it should work. 不是最好的解决方案,但我想它应该可以工作。 So idea in sort by user_id, so you will get unique pairs of conversation. 因此,请按user_id排序,这样您将获得唯一的对话对。
Select if(to_user_id > from_user_id, concat(from_user_id, ':', to_user_id), concat(to_user_id, ':', from_user_id)) as pair from messages group by pair;
This might work: 这可能起作用:
SELECT DISTINCT
if(to_user_id > from_user_id,to_user_id ,from_user_id) as source,
if(to_user_id > from_user_id,from_user_id,to_user_id ) as target
FROM conversations;
Probably not suitable to be part of anything more complex. 可能不适合做任何更复杂的事情。
I managed to join this up with data from the users
table with the below solution. 通过以下解决方案,我设法将其与users
表中的数据结合在一起。 Thought I would share. 以为我会分享。
Select O.Sender, S.First_Name, S.Last_Name, O.Target, T.First_Name,
T.LastName
From (
SELECT DISTINCT
if(to_user_id > from_user_id, to_user_id, from_user_id) as sender,
if(to_user_id > from_user_id, from_user_id, to_user_id ) as target
FROM chats AS pair
) O
LEFT JOIN Users S ON O.Sender = S.UserID
LEFT JOIN Users T ON O.Target = T.UserID
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.