TSQL内部选择使用外连接

时间:2014-11-25 22:14:09

标签: sql-server tsql stored-procedures sql-server-2012

我有一个大部分工作的查询,直到我必须为" Trainers"添加内部选择。

正如您在下面的代码中所看到的,我正在尝试为每个细分ID获取所有培训师。

我在第一个内部选择where子句WHERE trn.segmentID = tes.teSegmentID时收到错误,说明没有定义tes.teSegmentID。

是否有另一种方法来接近此查询以获得像我正在尝试完成的培训师?

SELECT *,
   (SELECT e2.[FirstName] AS trainerFirst,
           e2.[LastName] AS trainerLast
    FROM   BS_Training_Trainers AS trn
           LEFT OUTER JOIN
           employeeTable AS e2
           ON trn.trainerEmpID = e2.EmpID
    WHERE  trn.segmentID = tes.teSegmentID
    FOR    XML PATH ('trainer'), TYPE, ELEMENTS, ROOT ('trainers'))
FROM   dbo.BS_TrainingEvents AS a
WHERE  a.trainingEventID IN (SELECT tes.trainingEventID
                         FROM   dbo.BS_TrainingEvent_Segments AS tes
                                INNER JOIN
                                dbo.BS_TrainingEvent_SegmentDetails AS tesd
                                ON tesd.segmentID = tes.teSegmentID
                                INNER JOIN
                                dbo.BS_LocaleCodes AS locale
                                ON locale.localeID = tesd.localeID
                         WHERE  locale.location = 'Baltimore');

2 个答案:

答案 0 :(得分:0)

您似乎正沿着风景优美的路线前往:

SELECT a.*,
X.[FirstName],
X.[LastName]

FROM dbo.BS_TrainingEvents AS a
LEFT OUTER JOIN (SELECT e2.[FirstName], e2.[LastName], locale.location FROM dbo.BS_TrainingEvent_Segments AS tes 
                INNER JOIN dbo.BS_Training_Trainers AS trn ON trn.segmentID = tes.teSegmentID
                INNER JOIN dbo.BS_TrainingEvent_SegmentDetails AS tesd ON tesd.segmentID = tes.teSegmentID
                INNER JOIN dbo.BS_LocaleCodes AS locale ON locale.localeID = tesd.localeID
                LEFT OUTER JOIN employeeTable AS e2 ON trn.trainerEmpID = e2.EmpID) AS X ON a.trainingEventID = X.trainingEventID

WHERE  X.location = 'Baltimore';

不确定我是否正确连接了所有这些连接,很难从所有嵌套中解码。

答案 1 :(得分:0)

如果我正确地猜测了它们名称中的表关系,解决这个问题的唯一方法是引用相同的过滤条件两次:首先,在XML生成部分,第二个在查询的外层:

with cte as (
    select distinct tes.trainingEventID, tes.teSegmentID
    from dbo.BS_TrainingEvent_Segments AS tes
        INNER JOIN dbo.BS_TrainingEvent_SegmentDetails AS tesd ON tesd.segmentID = tes.teSegmentID
        INNER JOIN dbo.BS_LocaleCodes AS locale ON locale.localeID = tesd.localeID
    WHERE locale.location = 'Baltimore'
)
SELECT a.*, (
    SELECT e2.[FirstName] AS trainerFirst, e2.[LastName] AS trainerLast
    FROM BS_Training_Trainers AS trn
        LEFT OUTER JOIN employeeTable AS e2 ON trn.trainerEmpID = e2.EmpID
        inner join cte c on trn.segmentID = c.teSegmentID
    FOR XML PATH ('trainer'), TYPE, ELEMENTS, ROOT ('trainers')
    )
FROM dbo.BS_TrainingEvents AS a
where exists (select 0 from cte c where c.testrainingEventID = a.trainingEventID);

当然,很难说这是否完全正确,但我希望你明白这一点。

哦,是的,如果你有一个有多个巴尔的摩片段的活动,你将永远无法分辨哪个培训师需要哪一个。但是,您始终可以将更多数据添加到XML中以解决此问题。