【问题标题】:Insert data from multiple non-joinable tables从多个不可连接的表中插入数据
【发布时间】:2011-04-18 20:32:17
【问题描述】:

我在 Oracle 9i 数据库中有 3 个表。 A 与 B 连接,B 与 C 连接。A 和 C 没有什么可连接的。我正在尝试使用 A 和 C 中的值将行插入 B。我从这个开始:

INSERT INTO b
(value1, 
value2, 
value3, 
value4)
(SELECT 
a.value1,
a.value2,
c.value3, 
c.value4
FROM a, c 
WHERE a.column1 = x  
AND c.column2 = y)

但由于表 a 和 c 之间没有连接,因此插入的行数比我预期的要多得多。有没有办法拆分两个 select 语句以从 a 表中获取一些值,从 c 标准中获取其他值?如果是这样,语法是什么?

【问题讨论】:

  • 如果 a where col1 = x 只有一行,而 c where col2 = y 只有一行,这个输入应该只输入一行。如果 x 和 y 有多行,您将插入 x*y 行。您可以尝试 Select Distinct,但如果任何行的值 1-4 不同,仍然会有倍数。
  • 你为什么要使用隐含的连接语法?非常非常糟糕的编码习惯。

标签: sql insert oracle9i


【解决方案1】:

由于 A 和 C 之间没有关系,连接基本上是笛卡尔连接。

您添加的任何条件都将针对您的要求。如果您可以发布表格中的一些数据,这将有助于理解您的情况。

假设您有 2 个表 Student(10 行)和 Classes(3 行),您现在想要将行插入第三个表 (student_class_enrol)。除非您有一些特定条件,否则基本插入将是...

insert into student_class_enrol (student_id, class_id)
select s.student_id, c.class_id
  from students s, classes c;

这将插入 30 行,为所有 3 个班级的每个学生注册。

为避免这种笛卡尔“情况”,您可以像在问题中一样直接在查询后添加条件...

insert into student_class_enrol (student_id, class_id)
    select s.student_id, c.class_id
      from students s, classes c
      where (s.student_id not in (1,2,3) and c.class_id <> 4) ;

或单独添加条件,然后进行连接..

insert into student_class_enrol (student_id, class_id)
    select s.student_id, c.class_id
      from (select student_id from students where student_id not in (1,2,3)) s
           (select class_id from class where class_id <> 4) c;

【讨论】:

  • 基于“获得更多行......”我认为问题是如何避免笛卡尔积。
猜你喜欢
  • 1970-01-01
  • 2015-07-02
  • 2020-09-28
  • 1970-01-01
  • 1970-01-01
  • 2013-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多