2012-04-03 39 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) 
) 

如何將一個比較Table 1和Table彼此,建立關係表,查詢其x_random_attribute的是等​​價的,如果是這樣,存儲每一個主鍵在新的關係表?

回答

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允許你CREATE TABLE AS SELECT ...在一個聲明中
  • SQL服務器/的Sybase有SELECT .. INTO ...
+0

因爲我在MySQL這樣做,我可以這樣做: CREATE TABLE無論( first_id詮釋NOT NULL, second_id詮釋NOT NULL, common_random_attribute VARCHAR(255) ) AS SELECT ...(你在上面寫的是什麼?) – snotyak 2012-04-03 07:57:45

+0

@BackpackOnHead:沒有'CREATE TABLE Whatever AS SELECT ...'。 AFAIK你不能指定列/類型等,當你使用一個選擇 – gbn 2012-04-03 08:11:50

+0

我嘗試它的方式,我寫它(在這個答覆),它的工作!非常感謝! – snotyak 2012-04-03 08:41:16

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 
相關問題