我如何选择这个查询的逆,为什么我的尝试失败了......
要反转的查询:
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 数据库。直接的 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 不像 'anything'
会返回 NULL。
关于mysql - 我如何选择此查询的逆?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44011055/