【问题标题】:Update a column only if value of two columns(combination of both) are present else insert all values in Oracle DB仅当存在两列(两者的组合)的值时才更新列,否则将所有值插入 Oracle DB
【发布时间】:2018-04-28 13:54:21
【问题描述】:

在我的 Oracle DB 中,表 'basic_comment' 中有 3 列,列是 (product_id,comment,comment_id)。

只有当列(product_id 和comment_id)的组合已经存在时,我才必须更新列“comment”,否则在所有三列中插入。例如:

product_id     comment     comment_id  
Ac2108         fixed          5  
Ac7108         configure      3  
As2108         fixed          5  

因此,如果 (Ac2108 和 5) 存在,那么对于同一行,我需要将注释从 'fixed' 更改为 'configure',否则插入所有列。列将从另一个表插入"static_comment"
我尝试了合并查询,但它也在“basic_comment”表中更新其他行。

MERGE 
INTO  basic_comment a 
USING static_comment b
ON  ( a.product_id = b.product_id and a.comment_id = b.comment_id )    
WHEN MATCHED 
THEN 
 UPDATE
SET a.comment = b.comment
WHEN NOT MATCHED
THEN 
INSERT ( a.product_id
, a.comment
, a.comment_id
VALUES ( b.product_id
, b.comment
, b.comment_id);

【问题讨论】:

  • 我在您的查询中没有发现错误。您的查询只能更新条件( a.product_id = b.product_id and a.comment_id = b.comment_id ) 为真的行。表static_comment 包含多少行?
  • 为我工作...没有更新其他行。您绝对确定您提供了您真正使用的查询吗?例如,Oracle 中的列名不能是“comment”,并且您没有在 INSERT 语句中关闭括号(在 a.comment_id 之后)。请删除对 mysql 的引用,因为这是 Oracle 问题。
  • 如果这是Oracle,为什么我会看到MySQL标签??????请正确标记。

标签: sql oracle insert-update


【解决方案1】:

如果合并有问题,可以做两个单独的语句,显然没有那么快,但如果数据集很小,它会做

Update table
Set comment = ‘configure’
Where product_id is not null and comment_id is not null

Insert into table2(....,....)
Select comment_id, ‘static’
From table
Where not ( product_id is not null and comment_id is not null)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多