加入3个表时检索最后一条消息

时间:2014-12-09 15:08:47

标签: mysql

我目前正在从3个不同的表中检索数据。其中一个表包含与每个ID相关的消息。

我目前正在尝试但未成功的是检索每个ID记录的最后一条消息。

请帮助 -

select
   C.id ,
   C.business,
   AP.firstname,
   AP.lastname,
   M.comments,
   M.dateread 
from
   claims C 
JOIN
   affected_people AP 
      ON C.ID = AP.claimid 
join
   Messages M 
      on M.claimid = C.ID

2 个答案:

答案 0 :(得分:0)

不确定,如果适用于mysql:

select *
from(
    select
       C.id ,
       C.business,
       AP.firstname,
       AP.lastname,
       M.comments,
       M.dateread,
       max(M.dateread) over (partition by c.id)  max_dateread
    from
       claims C 
    JOIN
       affected_people AP 
          ON C.ID = AP.claimid 
    join
       Messages M 
          on M.claimid = C.ID)
          where max_dateread=dateread

答案 1 :(得分:-1)

只需加入

Order by M.dateread desc