java - SQLite - WHERE 子句中 IS 和 =(等于)的区别。 (使用 JDBC PreparedStatement)

标签 java sqlite comparison equals where-clause

编辑:与 a_horse_with_no_name 交谈我发现 SQLite 中的“IS”有点不同,允许使用“IS”比较 NULL 值:stackoverflow.com/a/9102445/1470058 .这为我消除了很多困惑。谢谢:

The IS and IS NOT operators work like = and != except when one or both of the operands are NULL. In this case, if both operands are NULL, then the IS operator evaluates to 1 (true) and the IS NOT operator evaluates to 0 (false). If one operand is NULL and the other is not, then the IS operator evaluates to 0 (false) and the IS NOT operator is 1 (true). It is not possible for an IS or IS NOT expression to evaluate to NULL. Operators IS and IS NOT have the same precedence as =.


我对 SQLite 中的关键字“IS”感到困惑。

我正在从事一个需要我使用 Java 准备好的语句的项目。我遇到过两种类型的 WHERE 子句:

SELECT * FROM table WHERE column = ?

SELECT * FROM table WHERE column IS NULL

我的问题是等号“=”和单词“IS”之间有区别吗? Google 搜索显示,大多数人使用 = 进行值比较,使用 IS 与 null 进行比较。但是,我自己尝试了一些 SQLite 查询。

  • “IS”将按预期返回“column IS NULL”和“column IS value”的结果。
  • “=”将按预期返回“column = value”的结果,但不会column = NULL”。

我的问题是,我可以在两种情况下都使用“IS”而不会出现意外结果吗?我想为单个查询制作一个准备好的语句,该查询对列的约束可能为 null,也可能不为 null。我希望我说得有道理。

为了简化我所说的一切,我可以使用以下 Java 代码而不会因使用“IS”而产生意外影响吗:

private static final String queryProjectSql = "SELECT * FROM fields WHERE project IS ?";
// later in a method
sqlStatement = connection.prepareStatement(queryProjectSql);
sqlStatement.setString(1, project); //Project may be a String or null

谢谢

最佳答案

上面的答案是错误的。他们说“=”必须在所有情况下使用,“IS”用于空值。文档不是这么说的。

文档说这两个运算符是等价的,唯一的区别在于它们计算 null 的方式。 = 两边的 NULL 将评估为 false。 IS 将评估 NULL 条件的真实性。

根据运算符的设计,此 NULL = NULL 将为假,而 NULL is NULL 将为真。

在某些情况下,您可能不关心列是否具有空值或是否具有与您的查询不匹配的合法值。在这种情况下,你会使用 = ... 并且在某些情况下你确实关心 null 在这种情况下你会使用 'is' 。

关于java - SQLite - WHERE 子句中 IS 和 =(等于)的区别。 (使用 JDBC PreparedStatement),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15233870/

相关文章:

java - 为什么这个数组中的所有元素都具有相同的值?

java - ClientHello 仅传递一种可用的密码套件,导致握手错误

java 可执行 jar 文件无法在另一台计算机上运行

java - Elasticsearch 扩展内部文档数组

android - SQLiteDiskIOException : disk I/O error (code 3850)

string - 多文本比较算法

android - 从 Android : Best Approach? 中的 4 个静态 CSV 文件读取数据

android - 没有 google api 的 INSTALL_FAILED_MISSING_SHARED_LIBRARY

c - 小于 void 指针的比较

c++ - 检查指针是否指向数组