2017-03-29 4 views
0

두 테이블 table1table2이 있습니다. 이러한 테이블에는 고유 한 nameid 열이 있습니다.다른 테이블에서 select를 사용하는 Oracle INSERT 문

또한 관계/조인 테이블 table1_table2은 직진 열이 table1_idtable2_id입니다. 내가 원하는 무엇

내가 대한 관계를 만들려면 table1table2에서 요소의 name들 알고 table1_table2에 새 관계를 삽입하는 것입니다. 하지만 idtable_table2에 삽입해야합니다. 나는 또한 또한 작동하지 않았다

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)) 

를 사용하여 시도

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

: 내가 원하는 무엇

은 같은 것입니다.

나는 필요한 경우 먼저 id을 추출 할 수 있음을 이해하지만 한 문장으로 작성하는 것이 좋습니다.

편집 : 나는 또한 또한 작동하지 않았다

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으로 설정하지만, Id o table1의 항목이 namebar이고 table2의 항목이 namedata 인 경우에만 알 수 있습니다.

+0

테이블 구조의 일부 샘플 데이터와 명확한보기가 도움이 될 수 있습니다. 이름이 일치하는 각 테이블의 ID를 원하십니까? ''이름 ''이 고정 된 것으로 표시되었으므로 모든 이름 또는 특정 이름에 대해? 이름이 하나 또는 다른 테이블에만 나타나는 경우에는 어떻게됩니까? –

+0

"작동하지 않는다"는 의미를 설명하십시오. –

답변

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') 
      ); 

을하지만, 내가로 작성합니다 : 표 1의 T1이 가입 FROM table1_table2 INTO

INSERT (table1_id, table2_id) SELECT t1.id, 을 t2.id를 table2 t2 ON t1.name = 'some_name'AND t2.name = 'another_name';

두 테이블 모두 일치하는 항목이 없으면이 경우 전혀 행이 삽입되지 않습니다. VALUES을 사용하면 NULL 값이 삽입됩니다.

+0

대단히 고맙습니다. –