2017-05-16 6 views
1

어떻게이 쿼리의 역을 선택합니까, 왜이 실패 내 시도 ...이 쿼리의 반대를 선택하려면 어떻게해야합니까?

쿼리 되돌릴 수 있습니다

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

내 시도 :

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

내가하려고 각각의 결과에 대해 ()를 계산하고 함께 추가합니다. 모든 행에 대한 총 수 ()를 얻지 못합니다. 항상 합계보다 적기 때문에 역을 선택하지 않는다는 것을 알고 있습니다. 나는 또한 내가 선택을 속이지 않는다는 것을 증명할 수 없다.

category_id 및 product_id가 정수가 될 수 있고 request_path가 string.empty 또는 null이 아닌 것으로 가정하십시오.

저는 .net 프로그래머입니다. 나는 아마 linq에서 이것을 꽤 쉽게 할 수 있었지만, 나는 mysql 데이터베이스를 고쳤다. Straight SQL은 항상 내 아킬레스 건이었습니다.

+3

'category_id is not null'** 및 **'product_id is not null '을 취소하지 않았습니다. 'category_id가 null이 아니거나 product_id가 null이 아닙니다.'. – ansh

+0

그리고 거기에 있습니다. – CarComp

+2

https://en.wikipedia.org/wiki/De_Morgan%27s_laws -하지만 간단히'where not (initial_condition)'을 사용할 수도 있습니다. –

답변

2

Transfering De Morgan's laws는 다음과 같은 규칙을 얻을 것이다 SQL로 :

을 : 당신이 or

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

and를 교체해야하지만 그것을 다음과 같은 방법을 쓰는 이유입니다

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

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

업데이트

Trinimons 코멘트가 정확한지 다음 request_path이 널 (null)을 포함 할 경우, null not like 'anything'는 NULL을 반환하기 때문에

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

해야

request_path like '%Portal%' 

의 정확한 반전.

+1

'request_path'가'null' 인 행에 대해서는 어떻게됩니까? 'null' 값은'something '이나'not like'something '과 같은 것이 아닙니다. See http://weblogs.sqlteam.com/markc/archive/2009/06/08/60929.aspx – Trinimon

+0

@Trinimon You' 맞아. 고마워. –