SQL自连接查询

时间:2013-02-07 12:27:03

标签: sql

我有四张桌子:

Service (serviceId(PK), serviceTypeId, capacity)
Facilitator (facilitatorId(PK), facilitatorName)
ServiceType (serviceTypeId(PK), serviceType)
ServiceFacilitator (serviceId(PK), facilitatorId(PK)) (join entity)

' ServiceType'中的服务类型目前的桌子是酒店和会议中心

&#39>容量' '服务'中的列table包含的数字whick仅在与ServiceType.serviceTypeId相关时才有意义,即根据服务类型表示床位或座位。

我需要编写一个返回3列的查询,nammely: 主持人名称,床位,席位

我几乎可以肯定,在存储过程中创建和丢弃临时表是一个糟糕的解决方案,可能会对未来的可伸缩性等产生负面影响,并且该解决方案涉及Service表上的自联接。

到目前为止,我的查询内容如下,但不返回任何行;我错过了什么?

SELECT f.facilitatorName,(SUM(ts1.capacity)) as Beds,(SUM(ts2.capacity)) as Seats

FROM dbo.Facilitator as f,
        dbo.TestService as ts1,
        dbo.TestService as ts2,
        dbo.ServiceFacilitator as sf

WHERE f.facilitatorId = sf.facilitatorId AND
        (sf.serviceId = ts1.serviceId or
        sf.serviceId = ts2.serviceId) and 
        ts1.serviceId = ts2.serviceId and
        ts1.serviceTypeId = '1' and -- type hotel
        ts2.serviceTypeId = '2' -- type conference centre           

GROUP BY f.facilitatorName

将查询分成两部分将返回床和座位的准确结果:

SELECT f.facilitatorName,(SUM(ts1.capacity)) as Beds

FROM dbo.Facilitator as f,
        dbo.TestService as ts1,
        dbo.ServiceFacilitator as sf

WHERE f.facilitatorId = sf.facilitatorId AND
        sf.serviceId = ts1.serviceId and 
        ts1.serviceTypeId = '1'         

GROUP BY f.facilitatorName

SELECT f.facilitatorName,(SUM(ts2.capacity)) as Seats

FROM dbo.Facilitator as f,
        dbo.TestService as ts2,
        dbo.ServiceFacilitator as sf

WHERE f.facilitatorId = sf.facilitatorId AND
        sf.serviceId = ts2.serviceId and 
        ts2.serviceTypeId = '2'         

GROUP BY f.facilitatorName

谢谢..

2 个答案:

答案 0 :(得分:3)

您的查询的简单解决方案应该是:

SELECT f.facilitatorName,
       SUM(case when ts.serviceTypeId = '1' then ts.capacity end) as Beds,
       SUM(case when ts.serviceTypeId = '2' then ts.capacity end) as Seats
FROM dbo.Facilitator as f
LEFT JOIN dbo.ServiceFacilitator as sf ON f.facilitatorId = sf.facilitatorId
LEFT JOIN dbo.TestService as ts ON sf.serviceId = ts.serviceId
GROUP BY f.facilitatorName

答案 1 :(得分:0)

您应该对此查询使用Join。 例如:

SELECT f.facilitatorName,(SUM(ts1.capacity)) as Beds,(SUM(ts2.capacity)) as Seats

FROM 
        dbo.ServiceFacilitator as sf 
join dbo.Facilitator as f 
on   sf.facilitatorI = f.facilitatorId
join dbo.TestService as ts1 
on sf.serviceId = ts1.serviceId
join  dbo.TestService as ts1
on sf.serviceId = ts2.serviceId

WHERE 
        ts1.serviceTypeId = '1' and -- type hotel
        ts2.serviceTypeId = '2' -- type conference centre           

GROUP BY f.facilitatorName