【问题标题】:How do i select the inverse of this query?我如何选择这个查询的逆?
【发布时间】:2017-05-16 20:32:35
【问题描述】:

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

要反转的查询:

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

【问题讨论】:

  • 你没有反转category_id is not null product_id is not null。让它category_id is not null OR product_id is not null.
  • 就是这样。
  • en.wikipedia.org/wiki/De_Morgan%27s_laws - 但你也可以简单地使用where not (initial_condition)

标签: mysql select inverse


【解决方案1】:

De Morgan's laws 传输到 SQL 会得到以下规则:

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

这就是为什么你需要用or替换and

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。

【讨论】:

猜你喜欢
  • 2019-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多