选择sql查询以合并结果

时间:2016-10-04 13:08:22

标签: sql

我有一张表old_data和一张表new_data。我想写一个给我的选择语句

  1. old_data中的行留在那里
  2. new_data中的新行会添加到old_data
  3. 唯一键为id,因此idnew_data的行应更新old_data
  4. 中的现有行

    我需要编写一个select语句,它会使old_data更新为新数据并添加新数据。

    示例:

    表a:

    id         count
    
    1             2
    2            19
    3             4
    

    表b:

    id         count
    
    2            22
    5             7
    

    我需要一个给我的SELECT语句

    id         count
    
    1             2
    2            22
    3             4
    5             7
    

3 个答案:

答案 0 :(得分:2)

根据您的预期结果:

        SELECT
             *
        FROM
             [TableB] AS B
        UNION ALL
        SELECT
             *
        FROM
             [TableA] AS A
        WHERE
             A.id NOT IN (SELECT id FROM [TableB])

答案 1 :(得分:2)

我认为这与COALESCE非常巧妙地合作:

SELECT a.id, COALESCE(b.count, a.count)
FROM a
FULL OUTER JOIN b
ON a.id = b.id

注意 - 如果您的RDBMS不包含COALESCE,您可以使用CASE写出函数,如下所示:

SELECT a.id,
CASE WHEN b.count IS NULL THEN a.count
ELSE b.count END AS count
FROM ...

您可以按如下方式编写FULL OUTER JOIN:

SELECT *
FROM a
LEFT JOIN b
ON a.id = b.id
UNION ALL
SELECT *
FROM b
LEFT a
ON b.id = a.id

答案 2 :(得分:0)

您必须使用UPSERT更新旧数据并在Old_data表中添加新数据,并从Old_data中选择所有行。检查以下内容并告诉我您对此查询的看法

UPDATE [old_data]
SET [count] = B.[count]
FROM [old_data] AS A
INNER JOIN [new_Data] AS B
ON A.[id] = B.[id]

INSERT INTO [old_data]
           ([id]
           ,[count])
SELECT A.[id]
     ,A.[count]
FROM [new_Data] AS A
LEFT JOIN [old_data] AS B 
ON A.[id] = B.[id]     
WHERE B.[id] IS NULL

SELECT *
FROM [old_data]