逻辑运算符 AND 和 OR

AND 和 OR 逻辑运算符会组合两个条件。当由 AND 关键字联接的两个条件都有匹配时,AND 评估为 TRUE,当由 OR 关键字联接的一个条件有匹配时,则 OR 评估为 TRUE。

OR 子查询(复杂表达式)

Vertica 支持使用 OR 的更复杂的表达式中的子查询,例如:

  • 连接表达式中有一个以上子查询:

    (SELECT MAX(b) FROM t1) + SELECT (MAX FROM t2) a IN (SELECT a FROM t1) OR b IN (SELECT x FROM t2)
    
  • 连接表达式中的 OR 子句至少包含一个子查询:

    a IN (SELECT a FROM t1) OR b IN (SELECT x FROM t2) a IN (SELECT a from t1) OR b = 5
    a = (SELECT MAX FROM t2) OR b = 5
    
  • 只有一个子查询,而且它包含在另一个表达式中:

    x IN (SELECT a FROM t1) = (x = (SELECT MAX FROM t2) (x IN (SELECT a FROM t1) IS NULL
    

如何评估 AND 查询

Vertica 会分别对待 AND(连接)运算符分隔的表达式。例如,如果 WHERE 子句为:

  WHERE (a IN (SELECT a FROM t1) OR b IN (SELECT x FROM t2)) AND (c IN (SELECT a FROM t1))

则将查询解释为两个连接表达式:

  1. (a IN (SELECT a FROM t1) OR b IN (SELECT x FROM t2))

  2. (c IN (SELECT a FROM t1))

第一个表达式会被认为是一个复杂的子查询,而第二个表达式则不会。

示例

以下列表显示了过滤 WHERE 子句中复杂条件的几种方法:

  • 子查询和非子查询条件之间的 OR 表达式:

    => SELECT x FROM t WHERE x > (SELECT SUM(DISTINCT x) FROM t GROUP BY y) OR x < 9;
    
  • 两个子查询之间的 OR 表达式:

    => SELECT * FROM t WHERE x=(SELECT x FROM t) OR EXISTS(SELECT x FROM tt);
    
  • 子查询表达式:

    => SELECT * FROM t WHERE x=(SELECT x FROM t)+1 OR x<>(SELECT x FROM t)+1;
    
  • 包含 [NOT] IN 子查询的 OR 表达式:

    => SELECT * FROM t WHERE NOT (EXISTS (SELECT x FROM t)) OR x >9;
    
  • 包含 IS [NOT] NULL 子查询的 OR 表达式:

    => SELECT * FROM t WHERE (SELECT * FROM t)IS NULL OR (SELECT * FROM tt)IS NULL;
    
  • 包含 boolean 列和返回 Boolean 数据类型的子查询的 OR 表达式:

    => SELECT * FROM t2 WHERE x = (SELECT x FROM t2) OR x;
    
  • CASE 语句中的 OR 表达式:

    => SELECT * FROM t WHERE CASE WHEN x=1 THEN x > (SELECT * FROM t)
           OR x < (SELECT * FROM t2) END ;
    
  • 分析函数、NULL 处理函数、字符串函数、数学函数等等:

    => SELECT x FROM t WHERE x > (SELECT COALESCE (x,y) FROM t GROUP BY x,y) OR
           x < 9;
    
  • 在用户定义的函数(假设 f() 为 1)中:

    => SELECT * FROM t WHERE x > 5 OR x = (SELECT f(x) FROM t);
    
  • 在不同的位置使用圆括号重建查询:

    => SELECT x FROM t WHERE (x = (SELECT x FROM t) AND y = (SELECT y FROM t))
           OR (SELECT x FROM t) =1;
    
  • 多列子查询:

    => SELECT * FROM t WHERE (x,y) = (SELECT x,y FROM t) OR x > 5;
    
  • 子查询左侧的常数/NULL:

    => SELECT * FROM t WHERE x > 5 OR 5 = (SELECT x FROM t);
    

另请参阅