2017-04-18 134 views
1

我試圖找出缺少必要版本的產品ID。 下面的查詢顯示的例子:如何(左/右)連接兩個表?

DECLARE @ProductWithVersion TABLE(ProductId int, VersionId int) 
insert into @ProductWithVersion values(1281,7),(2220,8) 

DECLARE @NecessaryVersion TABLE(VersionId int) 
insert into @NecessaryVersion values(7),(8),(9) 

我想告訴像映射結果:

ProductId  VerisonId  VersionId 
1281    7    7 
1281    null   8 
1281    null   9 
2220    null   7 
2220    8    8 
2220    null   9 

這意味着,從@NecessaryVersion的VERSIONID應該會全部顯示出來(7,8,9 ),並且@ProductWithVersion中的VersionId將顯示null如果不存在具有@NecessaryVersion的映射VersionId。

我想不出它,因爲它是複雜得多,左連接或右連接...

+0

應該不是'@NecessaryVersion '表還包含'ProducdId'? –

+0

如果有2個產品ID,您會希望得到什麼結果? – Lamak

回答

1

您需要的ProductId中介cross join像這樣:

select p.ProductId, pv.VersionId, n.VersionId 
from @NecessaryVersion n 
    cross join (select distinct ProductId from @ProductWithVersion i) as p 
    left join @ProductWithVersion pv 
    on p.ProductId = pv.ProductId 
    and n.VersionId = pv.VersionId 

rextester演示:http://rextester.com/VNITDI69180

回報:

+-----------+-----------+-----------+ 
| ProductId | VersionId | VersionId | 
+-----------+-----------+-----------+ 
|  1281 | 7   |   7 | 
|  1281 | NULL  |   8 | 
|  1281 | NULL  |   9 | 
+-----------+-----------+-----------+ 

如果您有一個表格,其中ProductId是唯一的,您可以使用該表格而不是從某個來源選擇distinct ProductId


有關更新後數據。例如,rextester演示:http://rextester.com/LVMFO44017

相同的查詢(具有order by)返回:

回報:

+-----------+-----------+-----------+ 
| ProductId | VersionId | VersionId | 
+-----------+-----------+-----------+ 
|  1281 | 7   |   7 | 
|  1281 | NULL  |   8 | 
|  1281 | NULL  |   9 | 
|  2220 | NULL  |   7 | 
|  2220 | 8   |   8 | 
|  2220 | NULL  |   9 | 
+-----------+-----------+-----------+ 
+0

謝謝,不用擔心「按順序排列」。你的作品很好! – user3174976

+0

@ user3174976樂意幫忙! – SqlZim