2017-05-16 3 views
1

どのように私はこのクエリの逆を選択するか、そしてなぜ私の試みは...逆にこのクエリの逆を選択するにはどうすればよいですか?

クエリ失敗している:私がしようとすると、

SELECT * FROM table_name 
where 
(category_id is not null and product_id is not null) 
and request_path not like '%Portal%'; 

SELECT * FROM table_name 
where (category_id is null and product_id is null) or request_path like '%Portal%'; 

私の試みをそれぞれの結果に()を数えて加算します。すべての行に対して合計数()が得られません。それは常に合計よりも小さいので、私は逆を選択していないことを知っています。私はまた、私は選択肢をdupingしていないことを証明することはできません。

category_idとproduct_idは整数で、request_pathは決してstring.emptyまたはnullではないとします。

私は.netプログラマです。私はおそらくlinqでこれをやっても簡単にできるかもしれませんが、私はmysqlデータベースを修正しています。ストレートSQLはいつも私のアキレス腱です。

+3

あなたは 'category_id is not null' **および**' product_id is not null 'を取り消しませんでした。 'category_idがヌルでないか、product_idがヌルでない'にします。 – ansh

+0

それがあります。 – CarComp

+2

https://en.wikipedia.org/wiki/De_Morgan%27s_laws - しかし、あなたは単に 'どこでもない(initial_condition)'を使うこともできます。 –

答えて

2

譲渡するDe Morgan's lawsあなたは以下のルールになるだろうSQLへ:

NOT (a AND b) = NOT a OR NOT b 
NOT (a OR b) = NOT a AND NOT b 

あなたはor

where (category_id is not null or product_id is not null) 
    and request_path not like '%Portal%' 

andを交換する必要がある。しかし、私はそれを次のように書くでしょう理由です:

where coalesce(category_id, product_id) is not null 
    and request_path not like '%Portal%' 

更新

Trinimonsコメントが正しい:null not like 'anything'はNULLを返しますので、request_pathはNULLを含めることができる場合は、

request_path like '%Portal%' 

の正しい反転は

(request_path not like '%Portal%' or request_path is null) 

でなければなりません。

+1

'request_path'が' null'の行はどうなりますか? 「ヌル」の値は「何か」「好きではない」「何かが好きではない」という意味ではありません。http://weblogs.sqlteam.com/markc/archive/2009/06/08/60929.aspx – Trinimon

+0

@Trinimon You 'よろしく - ありがとう。 –

関連する問題