2012-04-03 4 views
1

したがって、TABLE1とTABLE2があるとします。2テーブル - 互いに照会し、各テーブルのpkを新しいテーブルに格納します

CREATE TABLE TABLE1 
(
first_id int NOT NULL, 
first_random_attribute varchar(255) 
primary key(first_id) 
) 

CREATE TABLE TABLE2 
(
second_id int NOT NULL, 
second_random_attribute varchar(255) 
primary key(second_id) 
) 

どのように、お互いにTABLE1とTABLE2を比較するリレーショナル表を作成し、そのx_random_attributeさんは同等であり、彼らがしている場合は、新しいリレーショナルテーブル内の各1の主キーを保存するかどうかをチェックしますか?

答えて

2

ポータブルSQL

CREATE TABLE Whatever (
    first_id int NOT NULL, 
    second_id int NOT NULL, 
    common_random_attribute varchar(255) 
); 

INSERT Whatever (first_id, second_id, common_random_attribute) 
SELECT 
    t1.first_id, t2.second_id, t1.first_random_attribute 
FROM 
    TABLE1 t1 
    JOIN 
    TABLE2 t2 ON t1.first_random_attribute = t2.second_random_attribute; 

具体的な代替案:

  • MySQLは
  • のSQL Server/Sybaseは持っている1つのステートメントでCREATE TABLE AS SELECT ...にあなたを可能にSELECT .. INTO ...
+0

私は、MySQLでこれをやっているので、私は何ができる: はTABLE何であれ( first_idがNULLでないint型、 second_idはNOT NULLをINT、 common_random_attributeのVARCHAR(255) )を作成 AS SELECT ...( – snotyak

+0

@BackpackOnHead:いいえ 'CREATE TABLE Whatever AS SELECT ...'。 AFAIK SELECT/SELECTを使用すると列/型などを指定することはできません – gbn

+0

私は(この返信で)書いた方法で試してみました。どうもありがとう! – snotyak

0
このような

多分何か:

CREATE TABLE RealatedTable(
    first_id int NOT NULL, 
    second_id int NOT NULL 
); 

INSERT INTO RealatedTable(first_id,second_id) 
SELECT 
    TABLE1.first_id, 
    TABLE2.second_id 
FROM 
    TABLE1 
JOIN TABLE2 
    ON TABLE1.first_random_attribute=second_random_attribute 
関連する問題