【问题标题】:sql case statement update based on other table基于其他表的sql case语句更新
【发布时间】:2014-01-14 21:03:15
【问题描述】:

我想根据另一个表 (table2) 中一个或多个字段的值更新表 (table1)。我相信这应该是一个 case 语句,但我不确定如何在一个语句中合并一个 case 语句和基于另一个表的 update 子句。这是我到目前为止所知道的不起作用的内容:

update table1 i, table2 s 
set i.sales = 'F'
where s.payment = 'Y'
and i.order_no = s.order_no;

我知道如何根据两个表进行选择,但这不是很有帮助,因为我不想创建新的数据库对象 - 我只想更新现有对象 (table1):

create or replace view merge as
select
i.order_no
, case when s.payment = 'Y'
then 'F'
end as sales
from table1 i, table2 s
where i.order_no = s.order_no;

而且我知道如何在 case 语句中更新:

UPDATE  table1
SET     sales = (
                 SELECT  CASE 
                            WHEN  foo = 'X'  
                            THEN  'F'
                            ELSE  null
                           END     
                 FROM table1
                )
;

我考虑了 where 子句而不是 case 语句,但它最终选择了每条记录,并且第二张表在支付字段中肯定有不同的值:

update t1
set sales = 'F'
where exists (select table2.payment
          from table2
          where table2.order_no = table1.order_no
          and table2.payment = 'Y');

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

    试试这个:

    update table1 i
       set i.sales = (select case when x.payment = 'Y'
                                  then 'F'
                                  else i.sales end
                        from table2 x
                       where x.order_no = i.order_no);
    

    【讨论】:

    • 当我尝试这个时,我得到 ORA-01427:单行子查询返回多于一行
    • Table1 有很多列,相关的是 order_no 和 sales。 Table2 有很多列,相关的是 order_no 和 payment。
    • 那么 (table1 和 table2) 之间的关系是 1-N 吗?因为为了这项工作,你必须在那时之间有一个统一。此错误表明 table2 上有多个注册表与 table1 上的一个注册表相关。因此,如果关系 1-N 您必须为 table1 上的每个注册表定义条件以与 table2 上的一个相关
    【解决方案2】:

    我现在没有运行预言机(所以我无法正确检查语法),但我认为你可以尝试这样的事情:

    update table1 i
    set i.sales = 'F'
    where i.order_no IN (select s.order_no from table2 s where s.payment = 'Y')
    

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-11
      • 2022-01-18
      • 1970-01-01
      相关资源
      最近更新 更多