从两行中选择唯一ID

时间:2011-06-01 11:41:17

标签: mysql sql

好的,所以表格看起来像这样

owner_id | creator_id | receiver_id | content | created
1        | 1          | 2           | hoho    | 2011-27-05
2        | 1          | 2           | hoho    | 2011-27-05
1        | 2          | 1           | eoeo    | 2011-28-05
2        | 2          | 1           | eoeo    | 2011-28-05
1        | 1          | 3           | aaaa    | 2011-29-05
3        | 1          | 3           | aaaa    | 2011-29-05
2        | 2          | 3           | bbbb    | 2011-30-05
3        | 2          | 3           | bbbb    | 2011-30-05

我想要的是从每个creator_id或receiver_id中仅选择owner_id = 1的最后一条记录,无论是从creator_id还是receiver_id开始,只要它是唯一的creator_id或receiver_id所在的最后一条记录。 / p>

结果应该如下所示

owner_id | creator_id | receiver_id | content | created
1        | 1          | 3           | aaaa    | 2011-29-05
1        | 2          | 1           | eoeo    | 2011-28-05

1 个答案:

答案 0 :(得分:2)

首先获取每个owner_id的最后日期,creator_id:

select owner_id,
       creator_id as user_id,
       max(created) as max_created
from data
where owner_id = 1
group by owner_id, creator_id

每个owner_id相同,receiver_id:

select owner_id,
       receiver_id as user_id,
       max(created) as max_created
from data
where owner_id = 1
group by owner_id, receiver_id

然后结合并再次施加最大值:

select owner_id, user_id, max(max_created) as max_created
from (
     [the first of the above]
     union all
     [the second of the above]
     ) as users
group by owner_id, user_id

然后将其加入子查询:

select data.*
from data
join ([the union query above]) as max_dates
on max_dates.owner_id = data.owner_id
and max_dates.user_id in (data.creator_id, data.reporter_id)
and max_dates.max_created = data.created
where owner_id = 1 -- avoids scanning the whole table

这将产生最后出现creator_id的行,以及最后出现的reporter_id出现的行。

如果不删除有效行,则无法进一步减少它。假设返回的(创建者/报告者)对是(1,2)和(2,1)。如果您寻求每个用户的绝对最后一次出现,那么这两行都将被删除。