查询连接的差异

时间:2011-08-03 22:14:11

标签: tsql sql-server-2008

我有一个动态生成的查询。

SELECT '' + CAST(GalleryGallery_tGallery._Name AS VARCHAR(4000)) + '' AS NewName
FROM   Photographers_tGalleries
       LEFT OUTER JOIN Gallery_tGallery AS GalleryGallery_tGallery
         ON BaseContent_tGalleries.[Gallery] = GalleryGallery_tGallery._Guid
       LEFT OUTER JOIN BaseContent_tGalleries
         ON Photographers_tGalleries._Guid =
            BaseContent_tGalleries._Guid_Structure_Content  

这些联接对我来说是正确的。但是,查询错误为The multi-part identifier "BaseContent_tGalleries.Gallery" could not be bound.

以下查询确实有效。虽然连接匹配正确的字段,但它们的顺序不同。我想知道为什么这个有效,另一个没有。我们想修复前一个,但由于它是动态的,我正在寻找最少量的变化。

SELECT '' + CAST(GalleryGallery_tGallery._Name AS VARCHAR(4000)) + '' AS NewName
FROM   Gallery_tGallery AS GalleryGallery_tGallery
       LEFT OUTER JOIN BaseContent_tGalleries
         ON GalleryGallery_tGallery._Guid = BaseContent_tGalleries.Gallery
       LEFT OUTER JOIN Photographers_tGalleries
         ON BaseContent_tGalleries._Guid_Structure_Content =
            Photographers_tGalleries._Guid  

2 个答案:

答案 0 :(得分:3)

第一个查询不起作用,因为您尝试在ON语句中使用表BaseContent_tGalleries,但尚未加入。换句话说,您使用表作为连接条件,但表本身尚未连接。

答案 1 :(得分:3)

第一个查询的连接顺序错误。您需要在Gallery_tGallery之前引用BaseContent_tGalleries。

SELECT '' + CAST(g._Name AS VARCHAR(4000)) + '' AS NewName
FROM   Photographers_tGalleries AS g
       LEFT OUTER JOIN BaseContent_tGalleries AS b
         ON g._Guid = b._Guid_Structure_Content
       LEFT OUTER JOIN Gallery_tGallery AS gg
         ON b.[Gallery] = gg._Guid;

顺便提一下谁命名了你的表和别名? GalleryGallery_tGallery,真的吗?我已经转换为较短的别名来补偿真正喜欢打字的人。很多。