2014-09-04 69 views
0

这是我的查询。我删除了表格名称以及其他我选择的内容,以方便阅读。SQL查询 - 在另一个查询中使用信息

Select 
    b.Key1, 
    b.Key2 
From 
    b 

    left join c 
    on c.MailingKey = b.MailingKey 

    left join d 
    on d.OrderLineKey = c.OrderLineKey 

    left join e 
    on e.ShipKey = d.ShipKey 

    left join g 
    on d.ShipKey5 = g.ShipKey5 

    left join a 
    on a.DocKey = b.OrderKey 

    left join f 
    on f.pMethKey = b.MethKey 

我需要使用键1和键2,我选择另一个查询,以获取有关从另一个表键(位置,身份证等)的更多信息。我想我需要在这个原始查询中创建2个循环,并将它们全部加入。所以这样的事情:

Select b.Key1, b.Key2, h.*, i.* 
From b left join 
c on c.MailingKey = b.MailingKey left join 
d on d.OrderLineKey = c.OrderLineKey left join 
e on e.ShipKey = d.ShipKey left join 
g on d.ShipKey5 = g.ShipKey5 left join 
a on a.DocKey = b.OrderKey left join 
f on f.pMethKey = b.MethKey left join 
( 
Select* 
From table l 
Where ID = b.Key1 
) h left join ( 
Select* 
From table l 
Where ID = b.Key2 
) i 

我只是不知道如何写等于b.Key1和b.Key2。

我正在使用Microsoft Sql Server Management。

+2

采样数据W /预期的结果(这组内),将有助于。我还不明白这个问题。同样用简单的英语,描述你需要做的事情。你的意思是你需要使用这个作为一个表/视图加入?可以通用表表达式的工作(什么数据库mySQL,SQL Server,oracle /) – xQbert 2014-09-04 21:14:02

+0

避免循环,一个sql语句做到这一切。 – Twelfth 2014-09-04 21:16:48

回答

0

公共表表达式:

with cte as (
Select b.Key1, b.Key2 
From b left join 
c on c.MailingKey = b.MailingKey left join 
d on d.OrderLineKey = c.OrderLineKey left join 
e on e.ShipKey = d.ShipKey left join 
g on d.ShipKey5 = g.ShipKey5 left join 
a on a.DocKey = b.OrderKey left join 
f on f.pMethKey = b.MethKey) 
Select * from CTE 
INNER JOIN othertable o 
on b.key1=o.key1 
and b.key2=o.key2 

或你的意思是......

内嵌视图:

Select * 
from otherTable 
INNER JOIN (
Select b.Key1, b.Key2 
From b left join 
c on c.MailingKey = b.MailingKey left join 
d on d.OrderLineKey = c.OrderLineKey left join 
e on e.ShipKey = d.ShipKey left join 
g on d.ShipKey5 = g.ShipKey5 left join 
a on a.DocKey = b.OrderKey left join 
f on f.pMethKey = b.MethKey) CTE 
on b.key1=o.key1 
and b.key2=o.key2 

还是你的意思....别的东西?

也许是:使用OR语句......

Select * 
from otherTable o 
INNER JOIN (
Select b.Key1, b.Key2 
From b left join 
c on c.MailingKey = b.MailingKey left join 
d on d.OrderLineKey = c.OrderLineKey left join 
e on e.ShipKey = d.ShipKey left join 
g on d.ShipKey5 = g.ShipKey5 left join 
a on a.DocKey = b.OrderKey left join 
f on f.pMethKey = b.MethKey) CTE 
on o.key1=cte.key1 
OR o.key2=cte.key2 

或者也许......一个在声明

Select * 
from otherTable o 
INNER JOIN (
Select b.Key1, b.Key2 
From b left join 
c on c.MailingKey = b.MailingKey left join 
d on d.OrderLineKey = c.OrderLineKey left join 
e on e.ShipKey = d.ShipKey left join 
g on d.ShipKey5 = g.ShipKey5 left join 
a on a.DocKey = b.OrderKey left join 
f on f.pMethKey = b.MethKey) CTE 
on o.key1 IN (cte.key1, cte.key2) 
+0

这很接近,但我需要再次检查另一个表,但每次都使用不同的键。我在上面添加了一些代码来阐明我正在尝试做的事情。 – user2456259 2014-09-04 21:25:40

+0

你的意思是在“一套”或可能是“或”而不是“和”?上面的例子... – xQbert 2014-09-05 14:03:38