推进“AND NOT”查询

Posted

技术标签:

【中文标题】推进“AND NOT”查询【英文标题】:Propel "AND NOT" query 【发布时间】:2016-10-24 20:58:29 【问题描述】:

我在我的 php 应用程序中使用 propel ORM。

通过阅读文档,我不知道如何提出这种类型的请求:

SELECT x FROM table where col1 = 'xxx' and not(col2=1 AND col3=2);

使用纯推进逻辑执行此请求的最简洁方法是什么?

谢谢

【问题讨论】:

从逻辑上讲,这相当于 col1 = 'xxx' AND (col2 != 1 OR col3 != 2)... 这似乎用->combine(array('cond2', 'cond3'), 'or',...) 更容易表达,然后结合起来条件为 1,and。因为我是 DBA,所以我不能再提供帮助了……所以 ORM 是我的死敌。 感谢您的回答。我之前尝试过这种方式,使用 combine() 但我遇到了一个奇怪的行为: ->condition('cond1', 'x != ?', 1) ->condition('cond2', 'y != ?', 2 ) ->condition('cond3', 'z != ?', 3) ->combine(array('cond1', 'cond2', 'cond3'), 'or', 'cond12') 结果:SELECT .. . AND((x!=1 OR y!=2)OR z!=3) 这不是一回事.. 哎呀,我想有一个愚蠢的时刻,事实上,这完全是一回事...... 【参考方案1】:

您要查找的完整查询应该是这个:

$books = TableQuery::create()
    ->condition('cond1', 'col1 = ?', 'xxx')
    ->condition('cond2', 'col2 != ?', 1)
    ->condition('cond3', 'col3 != ?', 2)
    ->combine(array('cond2', 'cond3'), 'or', 'cond23')
    ->where(array('cond1', 'cond23'), 'and')
    ->find();

它创建:

一个 cond1 条件,其中 col1 = 'xxx' 一个 cond2 条件,其中 col2 != 1 一个 cond3 条件,其中 col3 != 2

然后它将 cond2cond3or 运算符组合在一个新的 cond23 中,这样

cond23 = cond2 or cond3

并将 cond23cond1and 运算符结合起来,这样最终的查询将是

where(cond1 and cond23)

【讨论】:

【参考方案2】:

您的查询相当于:

SELECT x FROM table where col1 = 'xxx' and (col2 != 1 OR col3 != 2);

假设您使用的是 propel 2,您应该能够完成您想要的:

$result = TableQuery::create()
    ->filterByCol1('xxx')
    ->filterByCol2(1, Criteria:NOT_EQUAL)
    ->_or()
    ->filterByCol3(2, Criteria:NOT_EQUAL)
    ->find();

【讨论】:

以上是关于推进“AND NOT”查询的主要内容,如果未能解决你的问题,请参考以下文章

mysql left join and not equals 应该只返回一行

SQL Server-聚焦LEFT JOIN...IS NULL AND NOT EXISTS性能分析(十七)

"and not" vs "or" t sql全文搜索

媒体查询详解

mysql基础二

测试基础推进-01-请求方法