2017-07-28 37 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

我投票添加主键 –