2014-03-05 103 views
-1

我有這個SQL查詢:SQL Server查詢,奇怪的行爲

SELECT UserChiamante.UserId as UserId 

FROM Something 

WHERE Something AND 
     UserChiamante.UserId = ChiamanteInterno.UtenteId 

的結果是這樣的:

_________________ 
|  UserId |  
|_______________| 
|  1008  | 
|---------------| 
|  1022  | 
|---------------| 
|  1032  | 
|_______________| 

而且它的確定。 但如果我更改查詢:

SELECT UserChiamante.UserId as UserId 

FROM Something 

WHERE Something AND 
     UserChiamante.UserId != ChiamanteInterno.UtenteId 

我期待一個不同的結果,但我得到一些奇怪的結果是這樣的:

_________________ 
|  UserId |  
|_______________| 
|  1008  | 
|---------------| 
|  1022  | 
|---------------| 
|  1032  | 
|---------------| 
|  1258  | 

的ID 1258是OK的,因爲我沒有在ChiamateInterno這個ID表,但其他3個在ChiamateInterno表中(obv,你可以從查詢的第一個版本中看到)。

OBV「UtenteId」其「用戶ID」的外鍵

那麼,爲什麼這個紀錄被選中?

+0

您的查詢語法錯誤。您必須提供完整的查詢以更好地理解問題。 –

+0

您可以擴展'Something'和'Something'嗎? 您正在實現一個連接,並可能嘗試執行一個外連接,但是您幾乎可以得到一個笛卡爾產品,因爲每行將被另一個表中的幾乎所有其他行連接。 –

回答

1

你應該真的顯示更多的查詢和樣本結果。

但是,我敢肯定,問題是你不完全理解聯接。畢竟,您甚至沒有在on子句中使用正確的join語法。一個很好的猜測是你想排除第二個表中的東西。

您所查詢的事:

where UserChiamante.UserId not in (select UtenteId from ChiamanteInterno) 

課程的確切語法和結構可能會有所不同,這取決於查詢的其餘部分。

+0

那麼工作 – Alist3r

0

我相信第一查詢看起來是這樣的:

SELECT UserChiamante.UserId as UserId 
FROM UserChiamante, ChiamanteInterno 
WHERE UserChiamante.UserId = ChiamanteInterno.UtenteId; 

首先,重寫這是一個明確的JOIN

SELECT UserChiamante.UserId as UserId 
FROM UserChiamante JOIN ChiamanteInterno ON 
     UserChiamante.UserId = ChiamanteInterno.UtenteId; 

那麼我想你需要在你的第二個查詢外連接。所以嘗試:

SELECT UserChiamante.UserId as UserId 
FROM UserChiamante LEFT JOIN ChiamanteInterno ON 
     UserChiamante.UserId = ChiamanteInterno.UtenteId 
WHERE UserChiamante.UserId IS NULL; 

或者可能是相反的方式。