2012-02-16 88 views
1

我有兩個表:如何合併SQL中的兩個表?

Table 1 = idhash - username - usermail 
Table 2 = idhash - views - fistseen - lastseen 

現在我想這些表合併到一個新表:

Table 3 = idhash - username - usermail - firstseen - lastseen 

*請注意,我要刪除的意見欄。

我試過了我在google上找到的解決方案,但到目前爲止他們似乎沒有工作。

  • 並非所有從表2中的idhash列有相應idhash表1 Stiil存儲那些「錯配」行空的用戶名和usermail
+0

你在使用什麼數據庫服務器? – 2012-02-16 15:08:06

+0

爲了澄清,您說表2中有表1中沒有相應行的行?我在問,因爲很多答案都是相反的。 – 2012-02-16 15:51:22

回答

3

該查詢會給你的結果:

SELECT A.*, B.firstseen, B.lastseen 
FROM [Table 1] A 
LEFT JOIN [Table 2] B 
ON A.idhash = B.idhash 

並插入和更新在你的表3的結果:

INSERT INTO [Table 3](idhash, username, usermail, firstseen, lastseen) 
SELECT A.*, B.firstseen, B.lastseen 
FROM [Table 1] A 
LEFT JOIN [Table 2] B 
ON A.idhash = B.idhash 
LEFT JOIN [Table 3] C 
ON A.idhash = C.idhash 
WHERE C.idhash IS NULL 

-- For SQL Server 
UPDATE T3 
SET firstseen = T1.firstseen, 
    lastseen = T1.lastseen 
FROM [Table 3] T3 
INNER JOIN (SELECT A.*, B.firstseen, B.lastseen 
      FROM [Table 1] A 
      LEFT JOIN [Table 2] B 
      ON A.idhash = B.idhash) T1 
WHERE T3.firstseen != T1.firstseen OR T3.lastseen != T1.lastseen 
+0

只是用'INSERT INTO [表3]'的前綴' – SuperSpy 2012-02-16 15:11:11

+0

@SuperSpy - 我剛剛更新了我的答案 – Lamak 2012-02-16 15:15:02

0

你可能只是蠻力它與您選擇的編程語言。只需構建一個新表,查詢兩個表,以編程方式連接行,但需要連接,插入到新表中。

0
insert into table3 
select t1.idhash, t1.username, t1.usermail, t2.firstseen,t2.lastseen 
from table1 t1 left join table2 t2 on t1.idhas=t2.idhas 
0

這應該是一個良好的開端。您需要告訴我們如何處理您的錯誤匹配記錄,然後才能提供更具體的信息。

Select 
    table1.idhash 
    ,username 
    ,usermail 
    ,firstseen 
    ,lastseen 
From table1 
    left join table2 
     on table1.idhash = table2.idhash 
0

這是非常接近蠻力。

select coalesce(t1.idhash, t2.idhash) as idhash 
, username 
, usermail 
, firstseen 
, lastseen 
into table3 
from table1 t1 
cross join table2 t2 
0

試試這個:

INSERT INTO table3 (idhash, username, usermail, firstseen, lastseen) 
SELECT a.idhash, a.username, a.usermail, 
     b.firstseen, b.lastseen 
FROM table1 a LEFT JOIN table2 b 
      ON a.idhash = b.idhash 
0

我這樣做:

  CREATE TABLE table3 
        AS 
       SELECT idhash, username, usermail, firstseen, lastseen 
        FROM Table1 
NATURAL FULL OUTER JOIN Table2 
1

下面是MySQL的一個解決方案:

CREATE TABLE table3 
// First get all the rows from table2, paired with matching rows from table1 
(SELECT a.idhash, b.username, b.usermail, a.firstseen, a.lastseen 
FROM table2 a 
LEFT JOIN table1 b 
    ON b.idhash = a.idhash) 
// Now get the remaining rows from table1 that don't have matches 
UNION ALL 
(SELECT null, a.username, a.usermail, null, null 
FROM table1 a 
LEFT JOIN table2 b 
    ON b.idhash = a.idhash 
WHERE b.idhash IS NULL) 

如果你不想讓行來自table1,在table2中沒有相應的行,然後刪除UNION子句中的第二個查詢。