2014-09-25 41 views
-1

我正在將數據庫結構轉換爲其他數據庫結構。 ID有這個問題。用於使用ID參照彼此的項目 - 但由於新結構不同,因此這些ID的必須更改爲一次對錶中的數字進行重新編號

所以,你有一個表(這是一個例子):

| id | ref | 
+----+-----+ 
| 1 | 3 | 
| 2 | 1 | 
| 3 | 1 | 
| 4 | 2 | 

現在,讓我們說,在新表中,ref ference ID必須像這樣的改變:

| old | new | 
+-----+-----+ 
| 1 | 2 | 
| 2 | 1 | 
| 3 | 4 | 
| 4 | 3 | 

見如果您隨後用UPDATE替換舊的ref會發生什麼情況:

Replacing: 1=>2 Replacing: 2=>1  This is what we need at the end: 
        well, damn 
| id | ref |  | id | ref |   | id | ref | 
+----+-----+  +----+-----+   +----+-----+ 
| 1 | 3 |  | 1 | 3 |   | 1 | 4 | 
| 2 | *2* |  | 2 | 2 |   | 2 | 2 | 
| 3 | *2* |  | 3 | 2 |   | 2 | 2 | 
| 4 | 2 |  | 4 | *2* |   | 2 | 1 | 

所以我需要一次替換它。我怎樣才能做到這一點?

+0

按照什麼標準確定1變成2而2變成1? – GolezTrol 2014-09-25 21:53:45

+0

@GolezTrol按標準將使這篇文章長3倍。沒關係。如果你真的感興趣,下面是關於我的特定數據庫的問題(http://stackoverflow.com/q/26002256/607407)案例。沒有人理解它 - 好運。 – 2014-09-25 22:03:05

+0

你聽起來像是我的問題,但對我來說,它似乎是你的。我對你的數據庫並不特別感興趣,我只是要求 - 我認爲是 - 爲你的問題提供一個很好的答案的必要信息。 – GolezTrol 2014-09-25 22:09:58

回答

0

由於標準不米atter,這將會訣竅。解決方案的核心是:一次更新所有行。

update YourTable 
set ref = 
    case ref 
     when 1 then 2 
     when 2 then 1 
     when 3 then 4 
     when 4 then 3 
    end 

如果這是不可能的:

  • 添加要包含新的IDS
  • 更新了「裁判一個新列 'newref' 以任何方式
  • 更新 'newref' '列中的值來自'newref'
  • 刪除'newref'
0

此更新所有在一個指令

UPDATE t1 a 
INNER JOIN t2 b 
ON a.ref=b.old 
SET a.ref=b.new; 

結果

select * from t1 

id ref 
1 4 
2 2 
3 2 
4 1 

http://sqlfiddle.com/#!2/ab49c/1

架構和數據樣本

create table t1 (id int, ref int); 
create table t2 (old int, new int); 

insert t1 values(1,3); 
insert t1 values(2,1); 
insert t1 values(3,1); 
insert t1 values(4,2); 

insert t2 values(1,2); 
insert t2 values(2,1); 
insert t2 values(3,4); 
insert t2 values(4,3); 
+0

@TomášZato你有沒有試過這個解決方案? – Horaciux 2014-09-26 01:36:46

+0

你的答案很好,但我沒有價值地圖表,所以我用'case'。但我相信它會幫助別人。順便說一下,您不必通過垃圾評論來提醒自己。我是幾年的活躍成員,我優雅地閱讀了我得到的答案。 – 2014-10-10 17:41:45

相關問題