对于措辞道歉,我无法真正找到另一种方式来表达它。
我有一个这样的历史表:
id date from_id to_id
1 2010-01-01 A B
1 2010-01-02 B C
1 2010-01-03 C D
2 2010-01-04 A B
2 2010-01-05 B X
2 2010-01-06 X Y
这表示id为#" 1"将转移自A-> B-> C-> D和" 2"在相应的日期转移为A-> B-> X-> Y.
现在,我想将此表格转换为"所有权历史记录"表格如下:
id date_from date_to owner_id
1 NULL 2010-01-01 A
1 2010-01-01 2010-01-02 B
1 2010-01-02 2010-01-03 C
1 2010-01-03 2010-01-04 D
1 2010-01-04 NULL D
2 NULL 2010-01-04 A
2 2010-01-04 2010-01-05 B
2 2010-01-05 2010-01-06 X
2 2010-01-06 NULL Y
使用MySQL有没有一种有效的方法呢?
截至目前,我已经得到了以下内容,尽管它非常非常缓慢:
select id, from_id as owner_id, date as date_from, (select date from table where from_id = h.to_id and id = h.id and date > h.date limit 1) as date_to from table h;
答案 0 :(得分:0)
您可以使用left join
:
select h.id, h.date as date_from, h2.date as date_to, h2.to_id
from history h left join
history h2
on h.id = h2.id and h.to_id = h2.from_id;
这只会留下每个id的初始记录。为此,请使用union all
:
select h.id, h.date as date_from, h2.date as date_to, h2.to_id
from history h left join
history h2
on h.id = h2.id and h.to_id = h2.from_id
union all
select h.id, NULL as date_from, h.date as date_to, h.id
from history h;