2017-03-22 11 views
3

マージ検索条件を理解しようとしていて、次の問題が発生しました。マージ検索複数条件 - SQL Server

表1

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

表2は

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

Iは、ターゲットテーブルのidの両方に存在するだけでグループID = 20本で(表2)標的とするソース(TABLE1)をマージしようとします。ここで

は、(検索条件をマージ私は

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 

あるしかし、私はON句の100%を確認していないものです)target.id = source.id and target.groupid = 20を複数の条件でチェックします。結果は常に予測可能であり、これらの複数の条件で上記の期待と一致していますか?ここでの予測可能性の問題か、「一致した場合」の条件にtarget.groupId = 20を追加する必要がありますか?

+0

さてあなたは、表2には、目標だったが、その後、クエリでソースとしてそれを使用しました。それ以外は私にはうまく見えます...これはWHERE句を書く別の方法です。 – scsimon

+1

table2、行2:id = 1ではないmispint? – Serg

+0

@ scsimon-タイプミスを指摘してくれてありがとう、同じ編集。 – 100pipers

答えて

4

あなたの参加が間違っているようです。 GROUPIDに参加する必要があるか、データが正しくありません。 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 

ON JOINING

そうでない場合、ID = 2ID = 1から行に "より良い" 相関する方法はありません。これは、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