2017-04-18 101 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