【问题标题】:insert all and inner join in oracle在oracle中插入所有和内部连接
【发布时间】:2019-01-31 02:40:39
【问题描述】:

我想将数据插入到两个表中。将是一对多的连接。为此,我当然必须使用外键。

我认为,table1 - ID 列是这个主键的理想选择。但我总是用触发器自动生成它,每一行。所以, 如何在同一个插入查询中将 Table1.ID(自动生成,主键)列放入 table2.Fkey 列?

INSERT ALL INTO table1 (   --here (before this) generated the table1.id column automatically with a trigger.
    table1.food,
    table1.drink,
    table1.shoe
) VALUES (
    'apple',
    'water',
    'slippers'
)
 INTO table2 (
    fkey,
    color
) VALUES (
    table1.id, -- I would like table2.fkey == table1.id this gave me error
    'blue'
) SELECT
    *
  FROM
    table1
    INNER JOIN table2 ON table1.id = table2.fkey;

错误信息: "00904. 00000 - "%s: invalid identifier""

【问题讨论】:

  • 可以用序列来创建id吗?
  • 错误消息还应显示 Oracle 认为“无效”的标识符。你能找到它并发回(在你的问题底部添加)吗?

标签: oracle join inner-join sql-insert oracle12c


【解决方案1】:

由于您使用的是 Oracle DB 的 12c 版本,因此可能会使用 Identity Column Property。然后在 table1 的插入语句之后通过 returning 子句轻松将第一个表 (table1) 的值返回到局部变量,并在下一个插入中使用table2 的声明如下:

SQL> create table table1(
  2                      ID    integer generated always as identity primary key,
  3                      food  varchar2(50), drink varchar2(50), shoe varchar2(50)
  4                      );

SQL> create table table2(
  2                      fkey  integer references table1(ID),
  3                      color varchar2(50)
  4                      );

SQL> declare
  2    cl_tab table1.id%type;
  3  begin
  4    insert into table1(food,drink,shoe) values('apple','water','slippers' )
  5    returning id into cl_tab;
  6    insert into table2 values(cl_tab,'blue');
  7  end;     
  8  /

SQL> select * from table1;

ID  FOOD    DRINK   SHOE
-- ------- ------- -------
 1  apple   water  slippers

SQL> select * from table2;

FKEY COLOR
---- --------------------------------------------------
   1 blue

无论何时您发出上述语句以在 beginend 之间进行插入,table1.IDtable2.fkey 列都将填充相同的整数值。顺便说一句,如果您在整个数据库中需要这些值(即也来自其他会话),请不要忘记通过插入提交更改。

【讨论】:

    【解决方案2】:

    按照@OldProgrammer 的建议,使用序列

    INSERT ALL INTO table1 (   --here (before this) generated the table1.id column automatically with a trigger.
        table1_id,
        table1.food,
        table1.drink,
        table1.shoe
    ) VALUES (
        <sequecename_table1>.nextval,
        'apple',
        'water',
        'slippers'
    )
     INTO table2 (
        fkey,
        color
    ) VALUES (    
        <sequecename_table2>.nextval,
        <sequecename_table1>.currval, -- returns the current value of a sequence.
        'blue'
    ) SELECT
        *
      FROM
        table1
        INNER JOIN table2 ON table1.id = table2.fkey;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-19
      • 2021-02-15
      • 2018-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-03
      相关资源
      最近更新 更多