MySQL - 将更改从一个表插入另一个表

时间:2012-04-19 15:14:31

标签: mysql sql select join insert

我有一张简化的表格:

id     date     color
----------------------
1   2012-01-01  black
2   2012-01-02  red
3   2012-01-03  red
4   2012-01-04  red
5   2012-01-05  green

现在我需要将此表中的颜色更改插入新表:

   date     before   now
----------------------------
2012-01-02  black    red
2012-01-04  red      green      

有人可以告诉我怎么样?

3 个答案:

答案 0 :(得分:3)

比较第二行与上一行:

SELECT cur.date, prev.color "before", cur.color now
FROM tbl cur
LEFT JOIN tbl prev ON cur.id = prev.id + 1
WHERE cur.id > 1 -- start detecting changes from second row
     AND prev.color <> cur.color

实时测试:http://sqlfiddle.com/#!2/0c146/1

修改

即使在非连续数据中也能正常工作。如果MySQL中有CTE功能,查询可能会更加简洁

create table tbl
(
  id int, 
  date date,
  color text
);


insert into tbl(id,date,color)
select 1,'2012-1-1','black' union
select 2,'2012-1-3','red' union
select 3,'2012-1-7','red' union
select 4,'2012-1-15','red' union
select 5,'2012-1-21','green' ;


set @rx = 0;
set @ry = 0;


select cur.date, prev.color as "before", cur.color as "now"

from (select *, @ry := @ry + 1 as series from tbl order by date) as cur 
left join (select *, @rx := @rx + 1 as series from tbl order by date) as prev
on cur.series = prev.series + 1

where cur.series > 1
and prev.color <> cur.color

实时测试:http://sqlfiddle.com/#!2/b9443/2

答案 1 :(得分:0)

首先,重命名color列 - &gt; before,然后添加now列(如果可能,default null),然后根据需要更新now列。

答案 2 :(得分:0)

如果我理解你,你需要存储过程。

Stored Procedures