Let's pretend I have the following "messages" table
ID (auto) Sender Receiver Msg Date (datetime)
1 Dave John Hi 01/01/2013
2 John Dave Hello 02/01/2013
3 James Dave U there? 02/02/2013
4 Dave James Yup 02/03/2013
5 Dave Simon Hey 02/03/2013
I want the list of people Dave is talking to ordered by Date.
Simon
James
John
I'm getting stuck on how to Group them without including "Dave" in one query.
Many thanks.
You seem to want the distinct list of people that Dave is talking to:
select (case when receiver = 'Dave' then Sender else Receiver end)
from messages m
where 'Dave' in (Receiver, Sender)
group by (case when receiver = 'Dave' then Sender else Receiver end)
order max(date) desc;
这将为您提供每个Dave已发送邮件到Date的消息并从Date收到消息的所有人。
SELECT DISTINCT(Receiver) FROM messages WHERE Sender = 'Dave' ORDER BY date DESC
SELECT Receiver FROM messages WHERE Sender = "Dave"
AND Receiver NOT IN (SELECT Sender FROM messages WHERE Receiver = "Dave")
UNION
SELECT Sender FROM messages WHERE Receiver = "Dave"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.