2012-08-26 14 views
4

我有兩個查詢。減號運算符在mysql中給我錯誤

首先查詢返回11行,第二個查詢返回6行,當我使用減號來對他們來說,應該儘量返回5行作爲我的理解

SELECT location from uploads where username='Gates' 
MINUS 
SELECT fileshare FROM `whiteboard` where username='Gates' and friend='Curlyclouds' 

但我得到以下錯誤:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'minus SELECT fileshare FROM whiteboard where username='Gates' and friend='Cur' at line 2

希望我的問題是明確的,任何幫助,將幫助我.....謝謝

回答

16

的MySQL不支持EXCEPTMINUS

您可以使用NOT EXISTS,OUTER JOIN ... NULLNOT IN(注意NULL)進行反半連接。

See examples and performance comparisons here

+0

我試過使用NOT EXITS代替零件 – user1529342

+2

等價的'NOT EXISTS'查詢應該看起來像'SELECT位置從uploads u where username ='Gates'且不存在(SELECT * FROM whiteboard w where w.username ='蓋茨'和w.friend ='Curlyclouds'和w.fileshare = u.location)' –

+0

嗨馬丁它工作.....非常感謝和歡呼 – user1529342

3

使用「沒有」或「不存在」對大數據集進行「減」查詢可能會導致非常長的查詢時間。我想出了一種模仿其他數據庫執行的基於集合的操作(合併,排序,刪除重複項)的方法。

select column1, count(*), min(setnum) 
from 
(
     select distinct column1, 1 as setnum 
     from table1 
    union all 
     select distinct column1, 2 as setnum 
     from table2 
) as tbl_a 
group by column1 
having count(*) = 1 and min(setnum) = 1 

上述選擇收益率大的數據非常不錯的表現將VS使用不存在或不是。從本質上講,它正在尋找,只有在第一組,而不是在第二個存在的行。最近我經常使用它,在性能方面取得了非常好的成績。