【问题标题】:SQL detect elements in OR clauseSQL 检测 OR 子句中的元素
【发布时间】:2014-07-08 21:45:27
【问题描述】:

我需要一个执行如下操作的 sql:

SELECT col1, col2, cond4 as cond4_is_exclusive
FROM table
WHERE (cond1 AND cond2 AND cond3) OR cond4

其中 cond4 = (col3 IN (...))

我需要 cond4_is_exclusive 为 TRUE,前提是 cond4 本身满足条件,而不是 cond1 和 cond2 和 cond3,因为它们之间存在 OR。

有这样的解决方案吗?

我需要一个优雅和优化的解决方案,因为查询更大,条件更多,更复杂。

我现在的工作是这样的:

SELECT col1, col2, (cond1 AND cond2 AND cond3) as c1, cond4 c2
    FROM table
    WHERE (cond1 AND cond2 AND cond3) OR cond4

后来c2和c2用php检查,不是那么优雅

【问题讨论】:

    标签: mysql sql postgresql


    【解决方案1】:

    以下内容应该适用于 Postgres(虽然不确定 MySQL - 我几乎从不使用它)

    select *
    from (
      SELECT col1, col2, 
             (cond1 AND cond2 AND cond3) as c1, 
             cond4 c2
      FROM table
    ) t
    WHERE c1 OR c2
    

    【讨论】:

    • 是的,或者对于更复杂的情况,使用 CTE(当然这在 MySQL 上不起作用)。
    • 这似乎是最好的。小抱怨:永远不要为 column 别名省略 ASQuote:But this is impractical for output column names, because of syntactic ambiguities.
    【解决方案2】:

    适用于两个数据库的解决方案是:

    SELECT col1, col2, cond4 as cond4_is_exclusive
    FROM table
    WHERE (cond1 AND cond2 AND cond3) and (not cond4) OR
          (not (cond1 AND cond2 AND cond3) and cond4);
    

    您也可以使用case 来表达这一点,因此您只需重复第一个条件一次:

    WHERE 1 = (case when (cond1 AND cond2 AND cond3)
                    then (case when cond4 then 1 else 0 end)
                    when cond4 then 1
                    else 0
               end)
    

    【讨论】:

      【解决方案3】:

      正如你在你的问题中所说的那样:你想要 ExclusiveOr 的东西。有一种东西叫...Exclusive or,即作为运营商:XOR

      A xor B 表示:A 为真,或B 为真,但绝不是两者兼而有之。

      SELECT col1, col2, cond4 as cond4_is_exclusive
      FROM table
      WHERE (cond1 AND cond2 AND cond3) XOR cond4
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多