我有一个表格结构,我会记录发送和接收的消息,如下所示;
member_id1是发件人,member_id2是接收者。
现在我要实现的是获取具有member_id为3的用户的最新消息的行。结果应该只包含2行,消息ID为2和4,因为2是member_id为3的用户与member_id为2的用户之间的最后一条消息,4是member_id为3的用户与member_id为1的用户之间的唯一消息。
结果不应包含message_id为3的行,因为它与member_id为3的用户无关,而message_id为1,因为message_id为2的消息已过期
希望我能帮助解决这个问题的人明白我的问题。
答案 0 :(得分:1)
我想我已经为自己的问题找到了正确的答案。虽然我不太确定,但似乎效果很好。对于那些需要解决这个问题的人;尝试一下:
SELECT m1.*
FROM table_name m1
INNER JOIN (SELECT MAX(senddate) AS senddate,
IF(member_id2 = 3, member_id1, member_id2 ) AS user
FROM table_name
WHERE (member_id1 = 3 AND delete1=0) OR
(member_id2 = 3 AND delete2=0)
GROUP BY user) m2
ON m1.senddate = m2.senddate AND
(m1.member_id1 = m2.user OR m1.member_id2 = m2.user)
WHERE (member_id1 = 3 AND delete1=0) OR
(member_id2 = 3 AND delete2=0)
ORDER BY m1.senddate DESC
答案 1 :(得分:0)
问题有点模糊,但据我所知,你在寻找这个?
SELECT * FROM table_name WHERE member_id2 = 3 ORDER BY senddate DESC;
答案 2 :(得分:0)
你可以使用UNION来组合它们
(SELECT * FROM table_name WHERE member_id2 = 3 ORDER BY senddate DESC limit 1)
union
(SELECT * FROM table_name WHERE member_id1 = 3 ORDER BY senddate DESC limit 1)
或者如果您需要为每个成员获取最新发送/接收的内容,您可以加入查询,获取每个成员的最大发送日期:
select * from table_name t1 inner join
(
select member_id1, null as member_id2, max(senddate) as senddate
from table_name group by member_id1
UNION
select null as member_id1, member_id2, max(senddate) as senddate
from table_name group by member_id2
) r ON (t1.member_id1 = r.member_id1 OR t1.member_id2 = r.member_id2)
AND t1.senddate = r.senddate