2
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

我只想要包含 59,72,83 的 mes_id 的响应,这是两个用户之间的最后一次对话。

请帮忙谢谢。

4

2 回答 2

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

SQLFiddle 演示

于 2012-10-18T06:47:24.483 回答
1

SQL小提琴

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
于 2012-10-18T12:29:51.133 回答