合并搜索多个条件 - SQL Server

时间:2017-03-22 18:36:58

标签: sql sql-server

我正在尝试了解合并搜索条件,并遇到了以下问题。

表1

id  groupid    description
-------------------------    
1     10       Good
2     20       Better

表2

id  groupid   description
-------------------------    
1    10       Very Good
1    20       Much Better

我打算将源(table1)和目标(table2)合并到两者中的id,但目标表中只有groupid = 20。

以下是我正在写的内容

Merge table1 source
Using table2 target ON (target.id = source.id AND target.groupid = 20)

When Matched
    Then update 
             set target.description = source.description

我期待的输出是

表2

id  groupid   description
-------------------------   
1     10      Very Good
1     20      Good

但我并不是100%肯定ON子句(合并搜索条件)有多个条件来检查target.id = source.id and target.groupid = 20。结果总是可以预测并且在这些多个条件下符合上述期望吗?或者可预测性是一个问题,我应该在"中添加target.groupId = 20时匹配AND"条件?

1 个答案:

答案 0 :(得分:4)

It looks like your join is wrong. You are either needing to join on the GROUPID or your data is incorrect.

JOINING ON GROUP

create table #table1 (id int, groupid int, description varchar(64))
create table #table2 (id int, groupid int, description varchar(64))

insert into #table1 values
(1,10,'Good'),
(2,20,'Better')


insert into #table2 values
(1,10,'Very Good'),
(1,20,'Much Better')


Merge #table2 t
Using #table1 s 
ON (t.groupid = s.groupid AND t.groupid = 20)
When Matched
Then update 
set t.description = s.description;

select * from #table2

drop table #table2
drop table #table1

Otherwise, there isn't any way to correlate "better" from ID = 2 to a row where ID = 1. This goes against your original join condition on the ID column.

BASED OFF EDITED EXPECTED OUTPUT

create table #table1 (id int, groupid int, description varchar(64))
create table #table2 (id int, groupid int, description varchar(64))

insert into #table1 values
(1,10,'Good'),
(2,20,'Better')


insert into #table2 values
(1,10,'Very Good'),
(1,20,'Much Better')


Merge #table2 t
Using #table1 s 
ON (t.id = s.id)         --you could also put the and t.groupid = 20 here...
When Matched and t.groupid = 20
Then update 
set t.description = s.description;

select * from #table2

drop table #table2
drop table #table1