代码之家  ›  专栏  ›  技术社区  ›  David542

IS TRUE运算符

  •  1
  • David542  · 技术社区  · 9 月前

    有多严格 IS TRUE SQL运算符应该是?例如,BigQuery只允许 BOOL 值,而我看到的其他方言也允许使用数字,例如mysql或postgres允许 select '1' is true ,尽管这可能只是出于历史原因,因为许多数据库不包括实际的 BOOL 数据类型。

    那么该怎么办 是真的 运算符允许作为操作数?

    1 回复  |  直到 9 月前
        1
  •  4
  •   Bill Karwin    9 月前

    严格按照SQL-99标准, IS 可以仅与相比 TRUE , FALSE UNKNOWN 阅读 https://sql-99.readthedocs.io/en/latest/chapters/09.html 详细信息。

    任何供应商的实施都可能偏离标准。例如,在MySQL中,true只是整数1的别名,false是整数0的别名。

    mysql> select true is true;
    +--------------+
    | true is true |
    +--------------+
    |            1 |
    +--------------+
    1 row in set (0.05 sec)
    
    mysql> select 1 is true;
    +-----------+
    | 1 is true |
    +-----------+
    |         1 |
    +-----------+
    1 row in set (0.03 sec)
    
    mysql> select '1' is true;
    +-------------+
    | '1' is true |
    +-------------+
    |           1 |
    +-------------+
    1 row in set (0.03 sec)
    

    SQLite还允许在数据类型方面有一定的灵活性。

    sqlite> select true is true;
    1
    sqlite> select 1 is true;
    1
    sqlite> select '1' is true;
    1
    

    PostgreSQL介于两者之间。字符串“1”被视为true,但整数1不是有效的操作数:

    postgres=# select true is true;
     ?column? 
    ----------
     t
    (1 row)
    
    postgres=# select '1' is true;
     ?column? 
    ----------
     t
    (1 row)
    
    postgres=# select 1 is true;
    ERROR:  argument of IS TRUE must be type boolean, not type integer
    LINE 1: select 1 is true;
                   ^
    

    SQL实现总是有自己的特点。你需要研究你使用的各个品牌的文档,甚至是确切的版本。