Mysql:事件表:按时间顺序连续加入

时间:2013-03-07 11:05:22

标签: mysql sql

我有下表:

user_id | Membership_type | start_Date
1       |         1       |      1
1       |         1       |      2
1       |         2       |      3
1       |         3       |      4

有几个用户,我需要找到每个用户的成员资格类型更改和更改的内容,采用以下格式(开始日期为datetime,将其放在int中以便于理解)

user_id |Membership_change| change_Date
1       |      1 to 2     |     3
1       |      2 to 3     |     4

我试过了

select m1.user_id, concat(m1.Membership_type, ' to ',m2.Membership_type), m2.start_date
from table_membership m1 
join table_membership m2
on m1.user_id=m2.user_id and m1.start_date<m2.start_date and m1.membership_type<>m2.membership_type

但这将返回

user_id |Membership_change| change_Date
1       |      1 to 2     |     3
1       |      1 to 2     |     3
1       |      1 to 3     |     4
1       |      2 to 3     |     4

复制1到2不是通过分组删除的问题,但我似乎无法想到避免产生1到3结果的方法。我基本上只需要按时间顺序从一个成员加入到下一个成员

任何想法都将不胜感激!

编辑:想要通过account_id和m1.start_date添加列m1.start_date和group,所以我只会获得每个条目连接的第一行。也是在连接之前按日期排序,以确保它们都是有序的。将测试。

2 个答案:

答案 0 :(得分:0)

您缺少GROUP BY

select
  m1.user_id,
  concat(m1.Membership_type, ' to ',m2.Membership_type),
  m2.start_date
from table_membership m1
  join table_membership m2
    on m1.user_id = m2.user_id
      and m1.start_date < m2.start_date
      and m1.membership_type <> m2.membership_type
GROUP BY user_id, Membership_change, change_Date

答案 1 :(得分:0)

有一个想法是通过account_id和m1.start_date添加列m1.start_date和group,所以我只会得到每个条目连接的第一行。也是在连接之前按日期排序,以确保它们都是有序的。

select m.user_id, m.membership_change, m.change_date from
(
select
  m1.user_id,
  concat(m1.Membership_type, ' to ',m2.Membership_type) as membership_change,
  m2.start_date as change_date, 
m1.start_date
from (select * from table_membership order by start_date asc)m1
  join (select * from table_membership order by start_date asc)m2
    on m1.user_id = m2.user_id
      and m1.start_date < m2.start_date
      and m1.membership_type <> m2.membership_type
GROUP BY m1.user_id,  m1.start_Date
)m group by 1,2,3