在oracle中插入所有和内部联接

在oracle中插入所有和内部联接,oracle,join,inner-join,sql-insert,oracle12c,Oracle,Join,Inner Join,Sql Insert,Oracle12c,我想在两个表中插入数据。将是一对多连接。为此,我必须使用外键,当然 我认为,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-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;
错误消息:
90400000-%s:@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;

因为您使用的是Oracle DB的12c版本,所以可能会使用Identity列属性。然后,通过在表1的insert语句之后使用return子句,轻松地将第一个表的表1的值返回到局部变量,并在下一个insert语句(表2的insert语句)中使用,如下所述:

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.ID和table2.fkey列都将由相同的整数值填充。顺便说一句,如果您在整个DBi过程中也需要这些值,请不要忘记通过插入提交更改。

是否可以使用序列创建id?错误消息还应显示Oracle认为无效的标识符。你能找到它并在你的问题的底部贴回add吗?