2016-09-23 78 views
1

我有一個用戶表。其中包括以下4列:如何連接表與自己,第二個「ON」條件,如果一行爲空

------ UserID ------- | ---- Username ----- | --- CreatedBy --- | ParentUserID

(PK,bigint,not null)| (char(20),not null)| (varchar(50),null)| (BIGINT,NULL)


兩個ParentUserID和CreatedBy點在 「擁有者帳戶」,分別由用戶ID或用戶名。兩者都是獨特的。

CreatedBy實際上從來沒有實際上是null,但UserID已編入索引,因此ParentUserID是首選 - 這也是我們正朝着這一目標邁進的一步。

顯然我不是精通SQL,但是這是我的想法是:

SELECT Users.* 
    FROM tblUsers AS Owners 
    LEFT JOIN tblUsers AS Users 
     ON 
     ISNULL(Users.ParentUserID = Owners.UserID, 
      Users.CreatedBy = Owners.Username) 
    WHERE Owners.UserID = 14; 

這是據我已經得到了:

SELECT ISNULL(POwners.UserID, COwners.UserID) AS OwnerID, Users.* 
    FROM tblUsers AS Users 
    RIGHT JOIN tblUsers AS POwners ON Users.ParentUserID = POwners.UserID 
    RIGHT JOIN tblUsers AS COwners ON Users.CreatedBy = COwners.Username 
WHERE OwnerID = 14; 

雖然顯然這並未」工作。在第二個說明中,我還需要將其轉換爲LINQ,但對於此問題,它僅與目前相關的查詢有可能進行轉換,這是我期望的絕大多數查詢。

回答

0

這似乎是沒有的伎倆,我查詢:

SELECT Users.* 
    FROM tblUsers AS Owners 
    LEFT JOIN tblUsers AS Users 
     ON Users.ParentUserID = Owners.ParentUserID 
     OR Users.CreatedBy = Owners.Username 
    WHERE Owners.UserID = 14; 

感謝Marc B的幫助。


至於LINQ,它變成了only equijoins are supported,所以我做了一個交叉連接這樣的:

from u in dbContext.tblUsers 
from o in dbContext.tblUsers 
where (u.ParentUserID == o.UserID || u.CreatedBy == o.Username) 
    && o.UserID == 14 
select u; 

這變成下面的查詢:

SELECT Users.* 
    FROM tblUsers AS Users 
     CROSS JOIN tblUsers AS Owners 
    WHERE(Users.ParentUserID = Owners.UserID OR Users.CreatedBy = Owners.Username) 
     AND(Owners.UserID = 14) 
0

join條件只是布爾測試,所以你需要編寫一個適當的布爾條件,例如, (P or Q) AND R。你不能,把它們連,所以......

... ON ISNULL((Users.ParentUserID = Owners.UserID) AND (Users.CreatedBy = Owners.Username)) 

或任何你需要的邏輯是。使其成爲有效的布爾表達式是關鍵部分。

+0

我用的是[ 'ISNULL(a,b)'](https://msdn.microsoft.com/en-us/library/ms184325.aspx),因爲我的印象是它使用第二個值,如果第一個值是'null'。類似於C#中的空合併運算符:'var user = firstUser ?? secondUser;'順便說一句,它應該讀取像'Users.ParentUserID = Owners.UserID或用戶.CreatedBy = Owners.Username' –

+1

你不能只是有'(a = b)或(C = d)'? –

+0

是的,這是一個有效的表達式 - 並返回正確的行數。但我不知道這是否正確,也不知道如何驗證。如果第一個條件爲真,它是否返回行,而不檢查第二個條件? –

相關問題