开发者

Difference in query joins

I have a query which is dynamically generated.

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 joins appear correct to me. However, the query errors with The multi-part identifier "BaseContent_tGalleries.Gallery" could not be bound.

The following query does work. While the joins are matching the correct fields, they are in a different order. I am wondering why this one works and the other does not. We would like to fix the top one but since it is dynamic, I am looking for the least amount of change.

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
  开发者_JS百科     LEFT OUTER JOIN Photographers_tGalleries
         ON BaseContent_tGalleries._Guid_Structure_Content =
            Photographers_tGalleries._Guid  


Your join ordering for the first query is wrong. You need to reference BaseContent_tGalleries before Gallery_tGallery.

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;

Who named your tables and aliases by the way? GalleryGallery_tGallery, really? I've converted to shorter aliases to compensate for whoever really likes typing. A LOT.


The first query doesn't work since you're trying to use the table BaseContent_tGalleries in an ON statement, but it has not been joined yet. In other words, you're using a table as a join condition, but the table itself hasn't been joined yet.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜