2012-04-19 107 views
0

我有一個簡單的表:MySQL的 - 插入從一個表切換到另一個

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  

人告訴我怎麼樣,拜託?

+0

這是功課?如果是這樣,你應該這樣標記。此外,你到目前爲止嘗試過哪些方法? – 2012-04-19 15:20:59

+0

輸出日期不明確,它指的是哪個日期? – 2012-04-19 15:31:15

回答

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

編輯

在非連續數據甚至工作。查詢可以,如果有CTE功能更succint在MySQL

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

+0

完美!謝謝。 – 2012-04-19 15:33:56

+0

哦,但是如果id = 4的行不存在,你的代碼將不再工作 – 2012-04-19 16:00:20

+0

如果MySQL支持CTE,我已經有了一個準備好的答案。 Postgresql,Oracle,SQL Server做的。我將檢查如何在MySQL – 2012-04-19 16:02:06

0

首先,重命名color柱 - >before,然後添加now柱(default null如果可能的話),然後根據需要更新now柱。