如何在SQL中合并两个表?

时间:2012-02-16 15:03:54

标签: mysql sql

我有两张桌子:

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

现在我想将这些表合并到一个新表中:

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

*请注意我要删除视图列。

我尝试过在谷歌上发现的解决方案,但到目前为止它们似乎没有用。

  • 并非表2中的所有idhash列都在表1中具有相应的idhash。Stiil使用空用户名和用户邮件存储那些“不匹配”的行

9 个答案:

答案 0 :(得分: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

答案 1 :(得分: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子句中的第二个查询。

答案 2 :(得分:0)

你可以用你选择的编程语言来强制它。只需构建一个新表,查询两个表,以编程方式连接行,但需要将它们连接起来,插入到新表中。

答案 3 :(得分: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

答案 4 :(得分:0)

这应该是一个好的开始。在我们提供更具体的内容之前,您需要告诉我们如何处理您的错误匹配记录。

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

答案 5 :(得分:0)

使用create statement

中的字段类型创建新表

http://www.w3schools.com/sql/sql_create_table.asp

然后执行insert Into Table3 <yourtable> select a.f1,b.f2,c.f3 from Table1 a, Table 2 b on a.id = b.id

答案 6 :(得分:0)

这非常接近蛮力。

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

答案 7 :(得分: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

答案 8 :(得分:0)

我会这样做:

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