2016-05-17 166 views
1

我試圖從alldocs(其中siteid =東西和結帳不爲空)的所有文件。 Alldocs有一個字段調用checkoutuserid,我需要從userinfo表中獲取名稱。 UserInfo可能有相同的ID重複,這就是爲什麼我添加站點ID。我收到以下查詢的錯誤。 「子查詢返回多個值)SQL查詢連接表 - 子查詢返回的值超過1

SELECT AllDocs.LeafName 
    , AllDocs.CheckoutDate 
    , UserInfo.tp_Title AS [User Name] 
    , UserInfo.tp_Login AS [User ID] 
    , UserInfo.tp_Email 
FROM AllDocs 
INNER JOIN UserInfo ON AllDocs.CheckoutUserId = (
     SELECT UserInfo.tp_ID 
     FROM UserInfo 
     WHERE UserInfo.tp_SiteID = 'E2FF98A7-B719-428D-8C30-856F08989691' 
    ) 
WHERE (AllDocs.SiteId = 'E2FF98A7-B719-428D-8C30-856F08989691') 
    AND (AllDocs.CheckoutUserId IS NOT NULL) 
ORDER BY AllDocs.LeafName 

我加入,我已經加了第三個表來查詢以下工作代碼。在正常使用下。

use WSS_Content_MMRHome1 
SELECT  distinct AllDocs.LeafName AS [File Name], AllDocs.dirName AS [Path], AllDocs.CheckoutDate, 
      UserInfo.tp_Title AS [User Name], UserInfo.tp_Login AS [User ID], 
      UserInfo.tp_Email AS [User Email], AllLists.tp_Title AS [List Name], ('http://inside.nv.com/'+AllDocs.DirName+'/'+AllDocs.LeafName) AS URL 
FROM  AllDocs 
      INNER JOIN UserInfo ON AllDocs.CheckoutUserId = UserInfo.tp_ID AND UserInfo.tp_SiteID = AllDocs.SiteId 
      INNER JOIN AllLists ON AllDocs.ListId = AllLists.tp_ID 
WHERE  AllDocs.SiteId = 'D36CCEA0-5351-4AEC-8B83-ACA2439CF38B' 
       AND AllDocs.CheckoutUserId IS NOT NULL 
ORDER BY AllDocs.LeafName 
+0

如果它應該多於一個值,請使用'in'而不是'=' - 或者修復您的sql以僅獲取一個值。你也可以使用'和exists(選擇1 ...'結構,它通常對性能更好,並且nulls不會導致問題。 –

回答

3

無需子查詢,只要將附加標準到join(或包括where子句中):

SELECT  distinct AllDocs.LeafName, AllDocs.CheckoutDate, 
      UserInfo.tp_Title AS [User Name], UserInfo.tp_Login AS [User ID], 
      UserInfo.tp_Email 
FROM  AllDocs INNER JOIN 
      UserInfo ON AllDocs.CheckoutUserId = UserInfo.tp_ID 
       AND UserInfo.tp_SiteID = 'E2FF98A7-B719-428D-8C30-856F08989691' 
WHERE  AllDocs.SiteId = 'E2FF98A7-B719-428D-8C30-856F08989691' 
       AND AllDocs.CheckoutUserId IS NOT NULL 
ORDER BY AllDocs.LeafName 

其實看起來像是同一個網站ID?如果是的話,只需加入該領域:

... 
FROM  AllDocs INNER JOIN 
      UserInfo ON AllDocs.CheckoutUserId = UserInfo.tp_ID 
       AND UserInfo.tp_SiteID = AllDocs.SiteId 
WHERE  AllDocs.SiteId = 'E2FF98A7-B719-428D-8C30-856F08989691' 
       AND AllDocs.CheckoutUserId IS NOT NULL 
ORDER BY AllDocs.LeafName 
+1

可能是真的,但是這*會產生重複的行 –

+0

@GordonLinoff - true,depends在這種情況下可能會有不同的結果...... – sgeddes

+0

這給了我alldocs中的重複行,但是如果我添加不同的行,它可以解決問題 –

相關問題