2017-07-28 41 views
0

如何更新兩個或更多重複行中的一個?我想保留一個並用新值更新其他人。更新Firebird中的兩個重複項 - 更多行

簡單的例子表:

one|two|three 
---------- 
1|milk|water 
1|milk|water 

one|two|three 
---------- 
1|milk|water 
1|milk|sugar 

回答

1

不知道你正在使用(解析功能支持如3.0版),火鳥的版本,如果以下語法是有效的(我目前無法驗證),您可以這樣做:

update table 
set three='sugar' 
where row_number() over (partition by one, two)=1 

否則,另一種更令人費解的方式做這將是:(未經測試)

select one, two, three 
from (
     select t1.one 
      ,t1.two 
      ,coalesce(t2.three, t1.three) as three 
      ,row_number() over (partition by t1.one, t1.two) as row_num 
     from table t1 
     left join (
       select one, two, 'sugar' as three, 1 as row_num 
       from (
         select distinct one, two, three 
         from table 
         group by one, two, three 
         having count(*) > 1 
         ) 
       ) t2 
     on t1.one=t2.one 
     and t1.two=t2.two 
     and t1.row_num=t2.row_num 
) 
2

http://www.ibexpert.net/ibe/index.php?n=Doc.TheMysteryOfRDBDBKEY

Select *, RDB$DB_KEY from MyExampleTable; 

然後

Update MyExampleTable 
    Set Column=Value 
    Where RDB$DB_KEY=xxxxx; 

另一種方法是是usin g存儲過程(或執行塊)並使用SQL遊標變量。但是這需要仔細的循環管理,所以你會跳過一行並更改第二,第三等。

https://www.firebirdsql.org/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-psql-coding.html#fblangref25-psql-tbl-declare-cursor

另請參見UPDATE ... WHERE CURRENT OF ...例子在 https://www.firebirdsql.org/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-dml-update.html#fblangref25-dml-tbl-update


但可能是最合適的方法是唯一的主鍵列添加到該表,然後使用唯一的數字ID

+2

我投票添加主鍵 –