Oracle Update Query - 两个表的连接

时间:2011-05-30 11:55:29

标签: oracle join sql-update

我有两个表,一个父表和一个子表。对于parent_id,子项将有很多行。两个表都有状态列。可能的值为“活动”和“已删除”。

我想这样做。如果对于父ID,所有子项都具有“已删除”状态,则必须将“父项”标记为“已从活动状态删除”。可以在单个更新查询中完成吗?

提前致谢。

3 个答案:

答案 0 :(得分:2)

这样的事情怎么样?

UPDATE parent_table pt SET deleted = 'Y' WHERE deleted = 'N' AND id NOT IN
    (SELECT parent_id FROM child_table ct WHERE deleted = 'N' AND ct.parent_id = pt.id)

答案 1 :(得分:1)

是:

update parent
   set status = 'Deleted'
 where status = 'Active'
   and not exists ( select null from child
                     where child.id = parent.id
                       and child.status <> 'Deleted')

答案 2 :(得分:1)

UPDATE parent_table 
set status = 'deleted'
WHERE status = 'active'
  AND id in (
              SELECT parent_id 
              FROM (
                    SELECT 
                            parent_id
                          , count(*)                                          total
                          , sum (CASE staus WHEN 'deleted' THEN 1 ELSE 0 END) deleted
                    FROM child_table
                    group by parent_id
              )
              WHERE total = deleted
             )