2012-01-02 31 views
-1

我有兩列:user_idgift_id。我期待返回結果集,其中user_id = 15906或其中gift_id = 15906,但不是其中user_id = gift_id用兩個不同的值返回結果集

因此,以下數據我應該得到兩個記錄。

user_id | gift_id 
-------------------------- 
15906 | null 
15906 | 15906 
12345 | 15906 

我想該組的第一個和最後一個記錄,而不是一個地方user_idgift_id匹配。

+0

我認爲第一行的空值導致問題。 – hcker2000 2012-01-03 14:07:25

回答

1

上述SQL語句的問題在於它們沒有考慮到SQL語句正在將int類型與NULL類型進行比較......大多數SQL語法分析器都不太喜歡這種情況。

嘗試xQbert的代碼,但使用coalesce功能

Select user_ID, Gift_ID 
FROM table 
WHERE (user_ID = 15906 or gift_ID=15906) and (user_ID <> coalesce(gift_id,0)) 

這將使它所以任何NULL轉換爲0適當comparisions。

+0

非常感謝您爲我解決問題的原因所作的良好回答和解釋。 – hcker2000 2012-01-03 14:19:40

0

也許使用組在事業解決問題:

select * FROM tablename where (user_id = 15906 or gift_id = 15906) and gift_id <> user_id 
+0

需要'FROM'子句。 – Lion 2012-01-02 22:00:10

2
Select user_ID, Gift_ID 
FROM table 
WHERE (user_ID = 15906 or gift_ID=15906) and (user_ID <> gift_ID) 
+0

這會返回第3行 – hcker2000 2012-01-03 13:56:47

2

最天作之合似乎xor

select user_id, gift_id 
from table1 
where (coalesce(user_id,0) = 15906) xor (coalesce(gift_id,0) = 15906) 

一個link, just in case.

+0

這會返回第3行 – hcker2000 2012-01-03 13:55:57

0
SELECT * FROM your_table 
WHERE (user_id = 15906 or gift_id = 15906) and gift_id <> user_id; 
+0

這會返回第3行 – hcker2000 2012-01-03 13:54:46

相關問題