您好我有以下更新查询:
UPDATE buchung b
SET kst_id = (SELECT kst_id
FROM kostenstelle
WHERE b.Kostenstelle = kostenstelle)
我在主题中得到错误,我知道原因。
我的问题:是否可以只更新唯一的行?
答案 0 :(得分:2)
有多种方法可以做到这一点。
添加WHERE
子句,检查特定b.kostenstelle
值是否只有表kostenstelle
中的一行:
update buchung b
set kst_id = (select kst_id
from kostenstelle
where b.Kostenstelle = kostenstelle)
where 1 = (select count(*)
from kostenstelle
where b.Kostenstelle = kostenstelle) ;
与以前完全一样,只使用不同的方式来检查一个。它可能更有效,索引在kostenstelle (kostenstelle, kst_id)
:
update buchung b
set kst_id = (select kst_id
from kostenstelle
where b.Kostenstelle = kostenstelle)
where not exists
( select 0
from kostenstelle
where b.Kostenstelle = kostenstelle
having min(kst_id) < max(kst_id) -- the PK of kostenstelle
) ;
使用COUNT()
窗口函数来确定计数:
with upd as
( select b.kst_id,
k.kst_id as k_kst_id
count(distinct k.kst_id) over (partition by k.kostenstelle) as cnt
from buchung b
join kostenstelle
on b.Kostenstelle = k.kostenstelle
)
update upd
set kst_id = k_kst_id
where cnt = 1 ;
以及最后一个的变体,其中代码的作用可能更明显:
with unq as
( select kostenstelle,
min(kst_id) as kst_id
from kostenstelle
group by kostenstelle
having min(kst_id) = max(kst_id)
) ,
upd as
( select b.kst_id,
k.kst_id as k_kst_id
from buchung b
join unq k
on b.Kostenstelle = k.kostenstelle
)
update upd
set kst_id = k_kst_id ;