mes_id subject mem_id frm_id
55 Hi 329 401
72 Re: HI yhi 689 401
83 Re: HEY HI 401 329
68 HI yhi 401 689
59 Hi 401 1734
您好, 请从下面的查询中找到我的表格回复,从中我得到1对1聊天消息的上述回复。
SELECT mes_id,SUBJECT,mem_id,frm_id
FROM messages_system_new
WHERE frm_id = '401' AND mem_id !='401'
AND trashed_user NOT LIKE '%401%'
AND TYPE = 'message'
AND FOLDER != 'saved' GROUP BY mem_id
UNION ALL
SELECT mes_id,SUBJECT,mem_id,frm_id
FROM messages_system_new
WHERE mem_id = '401' AND frm_id !='401'
AND trashed_user NOT LIKE '%401%'
AND TYPE = 'message'
AND FOLDER != 'saved' GROUP BY frm_id
我只想要包含mes_id为59,72,83的响应,这是两个用户之间的最后一次对话。
请帮忙 感谢。
答案 0 :(得分:1)
试试这个,
SELECT *
FROM Table1
WHERE (LEAST(mem_id, frm_id), GREATEST(mem_id, frm_id), mes_id) IN
(
SELECT LEAST(mem_id, frm_id) as x,
GREATEST(mem_id, frm_id) as y,
MAX(mes_id) as msg_time
FROM Table1
GROUP BY x, y
)
ORDER BY Mes_ID
答案 1 :(得分:1)
select t.*
from
table1 t
inner join (
select max(mes_id) as mes_id
from table1
group by least(mem_id, frm_id), greatest(mem_id, frm_id)
) s on t.mes_id = s.mes_id
where mem_id = 401 or frm_id = 401
order by mes_id