2

I'm working on a sql query that should 'coalesce' the records from 2 tables, i.e. if the record exists in table2, it should take that one, otherwise it should fall back to the values in table1.

In the example, table1 and table2 have just 2 fields (id an description), but obviously in reality there could be more.

Here's a small test case:

create table table1 (id int, description nvarchar(50))
create table table2 (id int, description nvarchar(50))

insert into table1 values (1, 'record 1')
insert into table1 values (2, 'record 2')
insert into table1 values (3, 'record 3')

insert into table2 values (1, 'record 1 modified')
insert into table2 values (2, null)

The result of the query should look like this:

1, "record 1 modified"
2, null
3, "record 3"

Here's what I came up with.

select 
  case when table2.id is not null then 
      table2.id else table1.id 
  end as Id,
  case when table2.id is not null then 
      table2.description 
  else 
      table1.description 
  end as Description
    -- etc for other fields
from table1
left join table2 on table1.id = table2.id

Is there a better way to achieve what I want? I don't think I can use coalesce since that would not select a null value from table2 if the corresponding value in table1 is not null.

4

2 回答 2

2

怎么样:

SELECT t2.ID, t2.Description
FROM table2 t2
UNION ALL
SELECT t1.ID, t1.Description
FROM table1 t1
WHERE NOT EXISTS (SELECT * 
                  FROM table2 t2
                  WHERE t2.ID = t1.ID)

上述查询从表 2 中获取所有记录(包括 description 为 NULL 但填充了 ID 的情况),并且仅从表 1 中获取它们在表 2 中不存在的记录。

于 2013-07-30T13:57:34.767 回答
1

这是一个替代方案:

SELECT table2.*
FROM table1
    RIGHT JOIN table2
        ON table1.id = table2.id

UNION

SELECT table1.*
FROM table1
    FULL OUTER join table2
        ON table1.id = table2.id
WHERE table1.id NOT IN (SELECT id FROM table2)
--and table2.id not in (select id from table1)

如果您不想要仅在 table2 中的 id,您可以添加最后一行。否则我猜 Stuart Ainsworth 的解决方案更好(即删除所有连接)

http://sqlfiddle.com/#!3/03bab/12/0

于 2013-07-30T13:59:12.970 回答