我有一个包含三个表的DB2数据库:locations
,items
,movement_history
。 items
表的外键location_id
为locations
。 movement_history
表在[{1}}中有一个外键item_id
,在items
中有两个外键location_id_before
和location_id_after
。< / p>
如果locations
或location
中没有行引用,我想删除items
。如果在某处引用了movement_history
行 ,我只想更新它以标记为已删除。有没有办法在一个声明中这样做?最好的方法是什么?
答案 0 :(得分:1)
尝试这样的命令:
MERGE INTO LOCATIONS AS LOC
USING (
SELECT Q1.ID, COALESCE(Q4.LOCATION_AFTER, Q3.LOCATION_BEFORE, Q2.LOCATION) AS ANY_REF
FROM LOCATIONS Q1
LEFT OUTER JOIN ITEMS Q2 ON Q2.LOCATION = Q1.ID
LEFT OUTER JOIN MOVEMENT_HISTORY Q3 ON Q3.LOCATION_BEFORE = Q1.ID
LEFT OUTER JOIN MOVEMENT_HISTORY Q4 ON Q4.LOCATION_AFTER = Q1.ID) AS T1
ON LOC.ID = T1.ID
WHEN MATCHED AND T1.ANY_REF IS NOT NULL THEN
UPDATE SET ACTUAL = 'N'
WHEN MATCHED AND T1.ANY_REF IS NULL THEN
DELETE