通过不同表中的外键引用

时间:2016-12-27 05:57:06

标签: database oracle foreign-keys

我有一个表T1,我想分成两个表,T2和T3。表T2包含来自T1的id和不同的名称。我想将数据插入到T3中,该字段具有字段ID,该字段是T2中id的外键。现在,当我从T1获取T3的数据时,它给出了我的名字,但我希望该列具有来自T2的相应id。

e.g。 t2是

// Example
// command1 -> Opening command for text program.
// command2 -> Executing the write and save command.(on above text program) 

popen = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
// next....?

现在从t1到t3的记录是

           1 | John
           2 | Jack
           3 | Jasper

现在我想在上面的表中使用1而不是John和2而不是Jack。

1 个答案:

答案 0 :(得分:1)

鉴于这些表......

SQL> select * from t1;

        ID PHONE                NAME           SALARY
---------- -------------------- ---------- ----------
       101 +9038302873          John              200
       102 +9023757583          Jack              500

SQL> select * from t2:

   NAME_ID NAME
---------- ----------
         1 John
         2 Jack
         3 Jasper

SQL> select * from t3;

no rows selected

SQL> 

...我们可以使用T1和T2上的连接填充T3,如下所示:

SQL> insert into t3
  2      ( id, phone, name_id, salary)
  3  select t1.id
  4          , t1.phone
  5          , t2.name_id
  6          , t1.salary
  7  from t1
  8       join t2
  9          on t1.name = t2.name
 10  /

2 rows created.

SQL> select * from t3;

        ID PHONE                   NAME_ID     SALARY
---------- -------------------- ---------- ----------
       101 +9038302873                   1        200
       102 +9023757583                   2        500

SQL> 

注意:您没有描述您的表格,所以我有即兴的列名称。您需要编辑INSERT语句以适合您的架构。

相关问题