存储过程(T-SQL)连接多个表

时间:2017-04-12 14:09:30

标签: sql sql-server tsql

我目前正在Microsoft SQL Server Management Studio(SQL Server)中处理t-sql查询,该查询应该通过多个表收集数据。最后,我需要[OfferId]和[Label]。您是否知道如何将这4个查询语句写入1?

SELECT a.OfferId AS [OfferId], a.OfferDataId AS [OfferDataId], b.DeliveryModelPoolId AS [DeliveryModelPoolId]
FROM [Offer].[Offer] a
INNER JOIN  [Offer].[OfferData] b
ON a.OfferDataId = b.OfferDataId

OfferId | OfferDataId | DeliveryModelPoolId
1 .......... | 1 .................. | 4

SELECT a.DeliveryModelPoolId AS [DeliveryModelPoolId], b.PoolId AS [PoolId]
FROM [Offer].[OfferData] a
INNER JOIN [Offer].[Pool] b
ON a.DeliveryModelPoolId = b.PoolId

DeliveryModelPoolId | PoolId
4 ................................ | 4

SELECT a.DeliveryModelId AS [DeliveryModelId]
FROM [Offer].[Delivery] a
INNER JOIN [Offer].[Pool] b
ON a.DeliveryModelPoolId = b.PoolId

DeliveryModelId
2
6

SELECT a.Label AS [Label]
FROM [Offer].[DeliveryModel] a
INNER JOIN [Offer].[DeliveryLabels] b
ON a.DeliveryModelId = b.DeliveryModelId

标签
服务中心
汽车送货

非常感谢! :)

2 个答案:

答案 0 :(得分:1)

如果您打算重复使用查询,我会将其放入视图中:

CREATE VIEW vWOfferData
AS   
SELECT a.offerID, dl.label
FROM [Offer].[Offer] a
INNER JOIN  [Offer].[OfferData] b
ON a.OfferDataId = b.OfferDataId
INNER JOIN [Offer].[Pool] p2
ON b.DeliveryModelPoolId = p2.PoolId
INNER JOIN [Offer].[Delivery] d3
ON d3.DeliveryModelPoolId = p2.PoolId
INNER JOIN [Offer].[DeliveryModel] dl
ON dl.DeliveryModelId = d3.DeliveryModelId

然后您可以将其用作表格。例如:

SELECT * FROM vWOfferData

答案 1 :(得分:0)

您可以在查询中多次加入

select a.offerID, dl.label
FROM [Offer].[Offer] a
INNER JOIN  [Offer].[OfferData] b
ON a.OfferDataId = b.OfferDataId
inner join [Offer].[Pool] p2
ON b.DeliveryModelPoolId = p2.PoolId
inner join [Offer].[Delivery] d3
ON d3.DeliveryModelPoolId = p2.PoolId
inner join [Offer].[DeliveryModel] dl
  on dl.DeliveryModelId = d3.DeliveryModelId