如何选择此查询的反转?

时间:2017-05-16 20:32:36

标签: mysql select inverse

如何选择此查询的反转,以及为什么我的尝试失败...

要反转的查询:

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一直是我的致命弱点。

1 个答案:

答案 0 :(得分:2)

De Morgan's laws转移到SQL,您将获得以下规则:

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

这就是您需要将and替换为or

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

但我会用以下方式写出来:

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

<强>更新

Trinimons评论是正确的:如果request_path可以包含NULL,则正确反转

request_path like '%Portal%'

应该是

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

因为null not like 'anything'将返回NULL。