在oracle中插入全部和内部联接

时间:2018-08-24 15:20:37

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

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

我认为,表1-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"

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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

每当您在上述 begin end 之间插入上述语句时,table1.IDtable2.fkey列都将填充相同的整数价值观。顺便说一句,如果您需要在整个数据库中使用这些值(例如,也需要其他会话),请不要忘记通过插入来提交