SELECT
S.SiteId,
B.FeatureInstance_Id BlogId,
P.FeatureInstance_Id PortfolioId,
C.FeatureInstance_Id PagesId
FROM
Sites S
LEFT JOIN (
SiteFeatures F1
INNER JOIN Blogs B ON F1.FeatureInstanceId = B.FeatureInstance_id
) ON S.SiteID = F1.SiteID
LEFT JOIN (
SiteFeatures F2
INNER JOIN Portfolios P ON F2.FeatureInstanceId = P.FeatureInstance_id
) ON S.SiteID = F2.SiteID
LEFT JOIN (
SiteFeatures F3
LEFT JOIN PageCollections C ON F3.FeatureInstanceId = C.FeatureInstance_id
) ON S.SiteID = F3.SiteID
這應該沒關係假設所有您的子表格每個FeatureInstance_Id
只能有一行。
如果您設計了數據庫,您在表格中列名不一致的情況下在指關節上獲得了良好的說唱效果。 :)
如果該查詢工作,那麼你可以考慮在一系列的意見,將查詢返回一個不錯的緊湊型封裝的事情是:
CREATE VIEW BlogsFeature
AS
SELECT
F.*
FROM
SiteFeatures F
WHERE EXISTS (-- or you could do an INNER JOIN, though in theory this is correct
SELECT 1
FROM Blogs B
WHERE F.FeatureInstanceId = B.FeatureInstance_id
)
這樣做的所有三個表將產生以下查詢:
SELECT
S.SiteId,
B.FeatureInstance_Id BlogId,
P.FeatureInstance_Id PortfolioId,
C.FeatureInstance_Id PagesId
FROM
Sites S
LEFT JOIN BlogsFeature B ON S.SiteID = B.SiteID
LEFT JOIN PortfoliosFeature P ON S.SiteID = P.SiteID
LEFT JOIN PageCollections C O ON S.SiteID = C.SiteID
其實,這使我想到另一種方式來表達你所需要的查詢,但它仍然不是很漂亮的前瞻性:
SELECT
S.SiteId,
F1.FeatureInstance_Id BlogId,
F2.FeatureInstance_Id PortfolioId,
F3.FeatureInstance_Id PagesId
FROM
Sites S
LEFT JOIN SiteFeatures F1
ON S.SiteID = F1.SiteID
AND EXISTS (
SELECT 1 FROM Blogs B
WHERE F1.FeatureInstanceId = B.FeatureInstance_id
)
LEFT JOIN SiteFeatures F2
ON S.SiteID = F2.SiteID
AND EXISTS (
SELECT 1 FROM Portfolios P
WHERE F2.FeatureInstanceId = P.FeatureInstance_id
)
LEFT JOIN SiteFeatures F3
ON S.SiteID = F3.SiteID
AND EXISTS (
SELECT 1 FROM PageCollections C
WHERE F3.FeatureInstanceId = C.FeatureInstance_id
)
如果您暫時將您的uniqueidentifiers轉換爲字符串,您仍然可以使用Max()方法。
SELECT
S.SiteId,
B.FeatureInstance_Id BlogId,
P.FeatureInstance_Id PortfolioId,
C.FeatureInstance_Id PagesId
FROM
SiteFeatures F
INNER JOIN Blogs B ON
你可以顯示你的表格結構和PK/FK關係嗎? – HLGEM 2011-06-06 16:25:08
你需要使用左外連接嗎?您的示例數據似乎是另有說明。 – dpmattingly 2011-06-06 16:28:49
對於給定的查詢,我無法想象我的生活如何獲得您的*初始*輸出。你確定你給我們的數據有代表性嗎? – 2011-06-06 16:46:52