【问题标题】:Oracle INSERT statement with selects on different tables在不同表上进行选择的 Oracle INSERT 语句
【发布时间】:2017-08-23 03:41:14
【问题描述】:

我有两张桌子table1table2。这些表具有唯一的 nameid 列。

我还有一个关系/连接表table1_table2,其中包含table1_idtable2_id 的直接列。

我想要做的是在知道table1table2 中的元素的names 中插入一个新关系到table1_table2 我想为其创建一个关系。但我需要让他们的ids 将它们插入table_table2

我想要的是这样的:

insert into table1_table2 values ((select id from table1 where name = 'some_name'), (select id from table2 where name = 'another_name'))

我也尝试过使用

insert into table1_table2 values ((select id from (select id from table1 where name = 'some_name') where rownum=1), (select id from (select id from table2 where name = 'another_name') where rownum=1))

这也没用。

我知道如有必要,我可以先提取 ids,但我希望它出现在一个语句中。

编辑:我也试过了

insert into table1_table2 values (select t1.id, t2.id from table1 t1, table2 t2 where t1.name = 'some_name' and t2.name = 'another_name')

这也没用

示例数据:

table1
id name
1  foo
2  bar

table2
id name
1  some
2  data

table1_table2
table1.id table2.id
1         1

现在我要插入

table1.id table2.id
2         2

进入table1_table2,但我只知道table1 中的条目有name bartable2 中的条目有name data

【问题讨论】:

  • 一些示例数据和更清晰的表结构视图可能会有所帮助。您是否想要名称匹配的每个表中的 ID - 对于所有名称或特定名称,因为您已将 'name' 显示为固定?如果一个名字只出现在一个或另一个表中怎么办?
  • 请解释“不起作用”是什么意思。

标签: sql oracle plsql relational-database oracle-xe


【解决方案1】:

这应该可行:

INSERT INTO table1_table2 (table1_id, table2_id)
    VALUES ( (SELECT id FROM table1 WHERE name = 'some_name'),
             (SELECT id FROM table2 WHERE name = 'another_name')
           );

但是,我会写成:

插入到 table1_table2 (table1_id, table2_id) 选择 t1.id,t2.id 从表 1 t1 加入 表2 t2 ON t1.name = 'some_name' AND t2.name = 'another_name';

请注意,在这种情况下,如果任一表中都没有匹配项,则根本不会插入任何行。使用VALUES,将插入NULL 值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    • 2018-05-14
    • 2012-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多