我如何 select 这个查询的逆?

How do i select the inverse of this query?

我如何select这个查询的反函数,为什么我的尝试失败了...

要反转的查询:

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%';

当我尝试对每个结果进行计数()并将它们加在一起时,我没有得到每一行的总计数()。它总是小于总数,所以我知道我没有 select 倒数。我也无法证明我没有欺骗 selection。

假设 category_id 和 product_id 可以是整数,并且 request_path 永远不会是 string.empty 或 null。

我是 .net 程序员。我可能可以在 linq 中很容易地做到这一点,但我正在修复一个 mysql 数据库。直 SQL 一直是我的致命弱点。

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' 将 return NULL。