简体   繁体   English

Oracle合并到…当不匹配时插入…-我可以使用别名吗

[英]Oracle Merge into … When not matched insert … - Can i use Alias

Here a simplified table example: 这里是一个简化的表格示例:

MAGIC_TABLE
titi | tata
-----------
val1 | magic1
val2 | magic2
val3 | magic1
val4 | magic1
val5 | magic2

What I want to achieve is that -> 我要实现的是->

For every row that have tata = 'magic2' and some value in titi if it does not exist a 'magic1' row with the same titi value then I should add a row with titi.value and 'magic1' 对于具有tata = 'magic2'且在titi有一些值的每一行,如果它不存在具有相同titi值'magic1'行,则我应添加带有titi.value'magic1'

Here is a simplified version of my SQL oracle query that I am working on : 这是我正在处理的SQL oracle查询的简化版本:

merge into MAGIC_TABLE magic
using (
    with UNMAGIC_TABLE as (
        select titi, tata from MAGIC_TABLE
        and tata='magic1'
    )
    SELECT titi, tata from UNMAGIC_TABLE 
) really_unmagic
on 
(
  magic.titi = really_unmagic.titi
  magic.tata = really_unmagic.tata
  and magic.tata='magic2'
) 
when not matched then insert (titi, tata) 
values 
(magic.titi, 'magic1');

Somehow I keep getting this error : 不知何故,我不断收到此错误:

ORA-38101: Invalid column in the INSERT VALUES Clause: "MAGIC"."TITI" ORA-38101:插入值子句中的无效列:“ MAGIC”。“ TITI”

So I was wondering if it is a syntax issue around aliases? 所以我想知道这是否是别名的语法问题? What did I do wrong there ? 我在那里做错了什么?

EDIT : It's an inattention error, as George Joseph pointed out I have to use unreally_magic to make it work, since when it's not matched I do not have lines from magic 编辑 :这是一个疏忽unreally_magic错误,正如乔治·约瑟夫(George Joseph)指出的那样,我必须使用unreally_magic才能使其正常工作,因为当它不匹配时,我就不会有magic线

If I were you, I'd write that merge statement like so: 如果我是你,我会像这样编写合并语句:

MERGE INTO magic_table tgt
USING (SELECT titi,
              'magic1' tata
       FROM   magic_table
       WHERE  tata = 'magic2') src
  ON (tgt.titi = src.titi AND tgt.tata = src.tata)
WHEN NOT MATCHED THEN
  INSERT (tgt.titi,
          tgt.tata)
  VALUES (src.titi,
          src.tata);

I don't know why but it seems I had to use really_unmagic to make it work, so I also had to change both where clause to have the correct wanted data in values . 我不知道为什么,但是似乎必须使用really_unmagic使其起作用,因此我还必须更改两个where子句以在values具有正确的所需数据。 But I still have no idea why the first query would not work. 但是我仍然不知道为什么第一个查询不起作用。

merge into MAGIC_TABLE magic
using (
    with UNMAGIC_TABLE as (
        select titi, tata from MAGIC_TABLE
        and tata='magic2'
    )
    SELECT titi, tata from UNMAGIC_TABLE 
) really_unmagic
on 
(
  magic.titi = really_unmagic.titi
  magic.tata = really_unmagic.tata
  and magic.tata='magic1'
) 
when not matched then insert (titi, tata) 
values 
(really_unmagic.titi, 'magic1');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM