我的cte和insert命令有什么问题

时间:2014-07-14 17:52:44

标签: sql join oracle11g common-table-expression

它只是一个内部连接和插入命令的基本cte不知道我做了什么错误请帮助

我的桌子t1

ID  Name
1   A
2   B
3   C

我的表t2

ID  Name
1   A
2   B

我想要做的是,内连接两个表并获取无与伦比的记录。将不匹配的记录插入表t2。这就是我写的

with scd(scdid,scdname)
as
(select t1.id as scdid, t1.name as scdname from t1 where t1.id not in (select t1.id from t1 inner join t2 on t1.id = t2.id))
insert into t2(id,name) select scd.scdid, scd.scdname from scd;

出了问题,它说

SQL Error: ORA-00928: missing SELECT keyword
00928. 00000 -  "missing SELECT keyword"

请帮忙,我想这一定是个简单的错误

编辑:为错误道歉,是的,我使用的是Oracle服务器。

1 个答案:

答案 0 :(得分:2)

以下是查询:

with scd(scdid, scdname) as
      (select t1.id as scdid, t1.name as scdname
       from t1
       where t1.id not in (select t1.id from t1 inner join t2 on t1.id = t2.id)
      )
insert into t2(id, name)
    select scd.scdid, scd.scdname
    from scd;

此查询在SQL语法上看起来在语法上是正确的。但是,您有Oracle错误。尝试将查询编写为:

insert into t2(id, name)
    select t1.id as scdid, t1.name as scdname
    from t1
    where t1.id not in (select t1.id from t1 inner join t2 on t1.id = t2.id);

或者更好的是:

insert into t2(id, name)
    select t1.id as scdid, t1.name as scdname
    from t1
    where t1.id not in (select t2.id from t2);

请注意,具有insert的CTE的Oracle语法是将with 放在<{em> insert之后。但是,这不需要CTE。

编辑:在Oracle语法中:

insert into t2(id, name)
with scd(scdid, scdname) as
      (select t1.id as scdid, t1.name as scdname
       from t1
       where t1.id not in (select t1.id from t1 inner join t2 on t1.id = t2.id)
      )
    select scd.scdid, scd.scdname
    from scd;

在Oracle中,with语句是select的一部分。