2014-06-07 64 views
0

我有一個SQL查詢 'q',其爲以下形式:如何計算SQL查詢的選擇謂詞的否定?

Select attribute from table1, table2 where SC; 

這裏SC'是所有選擇謂詞在q

會合在我的情況:SC is balance <1000 and salary >=50000

現在我想計算「NSC」這是否定SC in q並需要一些幫助。

+0

NSC餘額> = 1000,薪水<50000 – shazin

+0

不確定你在問什麼。我認爲'不是(平衡<1000和薪水> = 50000)'不是你想要的嗎?你問在MySQL中如何做'EXCEPT'? –

+0

我想要餘額> = 1000或工資> 50000.我想要知道如何找到這個或如何計算它的一般表達式 – user3395103

回答

0

每您的文章,你說i want to calculate "NSC" which is negation of SC和 SC是balance <1000 and salary >=50000

因此,SC的否定,簡直是balance >= 1000 and salary < 50000

所以,你可以像

Select attribute from table1 where balance >= 1000 and salary < 50000 

(OR)

Select attribute from table1 
where attribute not in 
(select attribute from table1 
where balance <1000 and salary >=50000) 
0

Ta你可以選擇兩種方法。

旁白:空

我會假設有在表或表達式不爲NULL。因爲這使事情變得複雜。特別是,如果我們想將NULL就好像它是在條件值,則:

v = w is true in SQL when v = w AND v IS NOT NULL AND w IS NOT NULL 
v != w is true in SQL when v != w AND v IS NOT NULL AND 

而且SQL有很多特殊的行爲時有空。另外要注意的是,空值是由SQL生成的,例如子查詢的OUTER JOIN和IN。見SQL and Relational Theory: How to Write Accurate SQL Code, 2nd Edition

1.不(表達式)

SQL不具有比較談-否定 「不」。你可以建立一個從頂部解析下來是另一種表達的不是表達式:

not (c AND d) is (not (c) OR not (d)) 
not (c OR d) is (not (c) AND not(d)) 
not (e NOT NOTable-operator o) is (e NOTable-operator o) 
not (e NOTable-operator o) is (e NOT NOTable-operator o) 
not (e NOT NOTable-function(f)) is (e NOTable-function(f)) 
not (e notable-function(f)) is (e NOT NOTable-function(f)) 
not (e != f) is (e = f) 
not (e = f) is (e != f) 
not (v < w) is is (v >= w) 
not NOT b is b -- boolean b 
not b is (NOT (b)) -- boolean b 

現在給SC你找到表達不(SC)和你寫的:

SELECT ... FROM ... WHERE not(SC) 

2。不不(表達)

在標準SQL中,你可以寫前面的查詢爲:

(SELECT ... FROM ...) 
EXCEPT 
(SELECT ... FROM ... WHERE SC) 

(在Oracle中它是MINUS。)但MySql沒有EXCEPT。但是s EXCEPT t

SELECT s.a,... 
FROM s 
LEFT JOIN t 
ON s.a = t.a AND ... 
WHERE t.a IS NULL 

當s.a在t中沒有匹配時,t.a是NULL。所以這隻返回不匹配的行。所以

SELECT ... FROM ... WHERE not(SC) 

是:

SELECT s.a,... 
FROM (SELECT ... FROM ...) s 
LEFT JOIN (SELECT ... FROM ... WHERE SC) t 
ON s.a = t.a AND ... 
WHERE t.a IS NULL 
0

你的問題的答案一般是由De Morgan's laws給出。

NOT(P AND Q) = NOT(P) OR NOT(Q) 

NOT(P OR Q) = NOT(P) AND NOT(Q) 

你表達NOT(balance < 1000 AND salary >= 50000)成爲

balance >= 1000 OR salary < 50000 

德摩根定律適用於布爾代數與二進制邏輯。如果你有NULL值,事情會變得更加複雜。要走的路要看你期待的結果。在這方面,一個非常有用的函數是COALESCE函數,它返回傳遞給它的第一個非空參數。

COALESCE(balance, 0) >= 1000 OR COALESCE(salary, 0) < 50000