2017-03-22 1 views
3

병합 검색 조건을 이해하려고하는데 다음과 같은 문제가 발생했습니다.여러 조건 병합 - SQL Server

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

표 2는

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

I 대상 테이블의 번호 모두에 존재하지만 그룹 ID = 20 본의 (표 2) 타겟 소스 (표 1) 병합하고자. 여기

내가 기대하고 출력은 표 2

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

입니다하지만 (검색 조건을 병합 ON 절 확신 100 % 아니다

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

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

을 쓰고 무엇인가) target.id = source.id and target.groupid = 20을 검사하는 여러 조건이 있습니다. 결과는 항상 예측 가능하며 이러한 여러 조건에서 위의 예상과 일치합니까? 또는 여기 예측 가능한 질문이며 "일치하는 경우"조건에 target.groupId = 20을 추가해야합니까?

+0

그럼 당신은 테이블이 대상했지만 다음 쿼리의 소스로 사용했다. 에 그렇지 않으면 내게 잘 보이는 ... WHERE 절을 쓰는 또 다른 방법입니다. – scsimon

+1

table2, row 2 : id = 1 not mispint? – Serg

+0

@ scsimon- 오타를 지적 해 주셔서 감사합니다. – 100pipers

답변

4

가입이 잘못되었다고 보입니다. GROUPID에 가입해야하거나 데이터가 올바르지 않습니다.

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 

그렇지 않은 그룹을 JOINING은 행 ID = 1ID = 2에서 "더 나은"상관 관계를 할 수있는 방법이 없다. 이는 ID 열의 원래 조인 조건에 반하는 것입니다.

을 기반으로 EDITED 예상 출력

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 
+0

@ scsimon- 출력을 다시보기 바랍니다. 질문을 편집했습니다. – 100pipers

+0

편집에 따라 @ 100pipers가 편집되었습니다 ... – scsimon

+0

@ scsimon- 재미있는 말은 편집 결과에 일치 조건이있을 때 t.groupid = 20을 넣은 것입니다. 나는 그것이 조건에뿐만 아니라 추가 할 수 있다는 귀하의 의견을 보았다. 성능과 관련된 구체적인 이유가 t.groupid = 20을 추가했을 때와 일치시킬 때 또는 일반적으로 맞습니까? – 100pipers