2012-05-23 47 views
1

有一個查詢:如何合併兩個生成的表使用由'a'字段的組由'b'字段的最大值?

select `privmsgs_id`, `contact`, `privmsgs_date`, `contentType` from (
    (
     select max(`privmsgs_id`) as `privmsgs_id`, `contact`, max(`privmsgs_date`) as `privmsgs_date`, `contentType` from (
      (
       select `privmsgs_from_userid` as `contact`, `privmsgs_id`, `privmsgs_date`, 'message' as `contentType` 
        from `privmsgs_table` 
       where `privmsgs_to_userid` = 305026 
      ) union (
       select `privmsgs_to_userid` as `contact`, `privmsgs_id`, `privmsgs_date`, 'message' as `contentType` 
        from `privmsgs_table` 
       where `privmsgs_from_userid` = 305026 
      ) 
     ) as `tmp` group by `contact` order by `privmsgs_date` desc 
    ) union (
     select max(`privmsgs_id`) as `privmsgs_id`, `contact`, max(`privmsgs_date`) as `privmsgs_date`, `contentType` from (
      (
       select `from_userid` as `contact`, `id` as `privmsgs_id`, `date` as `privmsgs_date`, 'postcard' as `contentType` 
        from `postcards_table` 
       where `to_userid` = 305026 
      ) union (
       select `to_userid` as `contact`, `id` as `privmsgs_id`, `date` as `privmsgs_date`, 'postcard' as `contentType` 
        from `postcards_table` 
       where `from_userid` = 305026 
      ) 
     ) as `tmp1` group by `contact` order by `privmsgs_date` desc 
    ) 
) as `rTmp` order by `privmsgs_date` desc; 

有兩個表tmptmp1工會合並,但增加了一倍場contact

privmsgs_id contact privmsgs_date contentType 
21490780 7070 1315207813  message 
21556868 7070 1315215266  postcard 
21226460 7754 1312025735  message 
21539085 15588 1314615528  postcard 
21489812 15588 1315208838  message 

所以,我只需要最後一個記錄(消息或明信片 - 不沒有問題)和最後一個記錄的ID(有問題 - 我可以在郵件和明信片單獨獲取最大(id),但不能在合併表中完成):

privmsgs_id contact privmsgs_date contentType 
21556868 7070 1315215266  postcard 
21226460 7754 1312025735  message 
21489812 15588 1315208838  message 

原因,爲什麼我不通過簡化查詢來做到這一點,因爲我需要特定數量的結果,因此,我只能通過一個查詢來完成此操作。

回答

0

您必須將結果分組爲contact並選擇最大值privmsgd_id,然後從中選擇僅來自privmsgd_id的信息。

查看GROUP BY瞭解更多信息。

+0

明信片和消息從分開的表中獲得,所以較舊的postard(按日期)的ID可能小於先前的消息ID。有問題 - 我不能通過不同的ID排序兩個不同的表。 – extempl

+0

我需要通過按「聯繫人」對記錄進行分組並按max(日期)進行排序來獲取實際ID。這是做到這一點的唯一方法,但我不知道如何。 – extempl