我想根据两列选择distinct,这样如果两列中的任何一列具有相同的值,那么它只会发布一次该行。如果它有助于你理解,我正在做一个发送者/接收者的事情,我只想拉一行(无论是发送者还是接收者)。
以下是我希望MySQL工作的方式:
SELECT DISTINCT(sender AND receiver), message, timestamp
FROM messages
WHERE receiver=receiver_name OR sender=sender_name;
示例:
消息表:
id| sender |receiver | message | timestamp
1 | Jeffrey | Michael | Hey man, what's up | 12:00 PM
2 | Michael | Jeffrey | Not much. How are you? | 12:02 PM
SQL查询后的结果:
迈克尔的最新消息:不多。你好吗?时间:下午12:02
我希望这有点道理
答案 0 :(得分:1)
从OP评论到Gordon Linoff的答案,似乎他有兴趣为他和其他人之间的每次转换检索最后一条消息,在这种情况下,发送者或接收者将是他
SET @myname = 'Michael' --just stick here your name
SELECT m.*
FROM messages m
INNER JOIN (SELECT MAX(ID) ID
FROM messages
WHERE @myname IN (receiver, sender)
GROUP BY COALESCE(NULLIF(receiver, @myname), sender)
) a ON m.ID = a.ID
公式COALESCE(NULLIF(receiver, @myname), sender)
将始终以另一个名称解析:
NULLIF(receiver, @myname)
将返回接收者,COALESCE
NULLIF(receiver, @myname)
将返回NULL
而COALESCE
将返回发件人答案 1 :(得分:0)
您需要使用concat函数。
SELECT distinct concat(sender,receiver)
FROM messages
WHERE receiver=receiver_name OR sender=sender_name;
有关详细信息,请参阅here。
答案 2 :(得分:0)
您的代码 -
SELECT DISTINCT(sender AND receiver), message, timestamp
FROM messages
WHERE receiver=receiver_name OR sender=sender_name;
新代码 -
SELECT DISTINCT (sender , receiver), message, timestamp
FROM messages
WHERE .........
答案 3 :(得分:0)
我想您要使用least()
和greatest()
:
select distinct least(sender, receiver), greatest(sender, receiver)
from messages;
如果您想要最新的时间戳,请使用group by
:
select least(sender, receiver), greatest(sender, receiver),
max(timestamp)
from messages
group by least(sender, receiver), greatest(sender, receiver);
编辑:
如果您想了解某人发送或接收的最后一封邮件的信息,您可以执行以下操作:
select m.*
from messages m
where not exists (select 1
from messages m2
where (m2.sender = m.sender or m2.receiver = m.receiver or
m2.receiver = m.receiver or m2.receiver = m.sender
) and
m2.timestamp > m.timestamp
);