【问题标题】:SQL doesn't return correct valuesSQL 不返回正确的值
【发布时间】:2018-03-14 15:21:57
【问题描述】:

所以,我有一个简单的 SQL 查询,但它似乎有问题(或者我的 where-clause 写错了),因为如果我在特定字段 (matflag) 上选择它不会返回值一个特定的值 (50)。

查询基本上是一个select from table1,在table2 上有一个子查询,其中where-clause 只是检查子查询的返回字段是否存在于table1

Select distinct  
    t1.matnum as matnum, t1.matflag as matflag, t1.factory as factory 
from 
    table1 t1, 
    (select matnum from table2 where technical_value = 'XX') t2 
where 
    t1.matnum = t2.matnum and t1.matnum = '60000000';

这会返回这个输出:

+----------+---------+---------+
| MATNUM   | MATFLAG | FACTORY |
+----------+---------+---------+
| 60000000 |         | 001000  |
| 60000000 |         | 002000  |
| 60000000 |         | 003000  |
| 60000000 |         | 004000  |
| 60000000 |         | 005000  |
+----------+---------+---------+

如果我将and t1.matflag != '50' 添加到where-clause 的末尾,整个输出就会消失。

Select distinct 
    t1.matnum as matnum, t1.matflag as matflag, t1.factory as factory 
from 
    table1 t1, 
    (select matnum from table2 where technical_value = 'XX') t2 
where 
    t1.matnum = t2.matnum 
    and t1.matnum = '60000000' 
    and t1.matflag != '50';

输出:

+----------+---------+---------+
| MATNUM   | MATFLAG | FACTORY |
+----------+---------+---------+

matflag 列的附加信息:它是一个 varchar2(2 Char) 列,要么填充任何内容,要么填充值“50”或值“10”或“20”。 现在,如果我将 where 子句从 and t1.matflag != '50' 更改为 and t1.matflag is null,则输出再次正确:

Select distinct 
    t1.matnum as matnum, t1.matflag as matflag, t1.factory as factory 
from 
    table1 t1, 
    (select matnum from table2 where technical_value = 'XX') t2 
where 
    t1.matnum = t2.matnum 
    and t1.matnum = '60000000' 
    and t1.matflag is null;

所以这会返回这个输出:

+----------+---------+---------+
| MATNUM   | MATFLAG | FACTORY |
+----------+---------+---------+
| 60000000 |         | 001000  |
+----------+---------+---------+
.... and so on, have a look at the first table above

如果我选择is null,但如果我选择!= '50',它会如何返回? (旁注:将!= 更改为<> 也无济于事)

matflag is null 如何适用但matflag != '50' 不适用?

我们运行 Oracle Database 11g 版本 11.2.0.3.0 - 64 位生产。

【问题讨论】:

  • 在 SQL 中NULL 表示“未知”值,因此对其进行操作将得到NULL,即BOOLEAN 化为FALSE....

标签: sql oracle11g


【解决方案1】:

了解如何使用正确的显式JOIN 语法:

Select distinct t1.matnum as matnum, t1.matflag as matflag, t1.factory as factory 
from table1 t1 join
     table2
     on t1.matnum = t2.matnum
where t2.technical_value = 'XX' and t1.matnum = '60000000';

然后了解 NULL 值以及它们如何在几乎所有比较中失败,包括 <>

你想要的逻辑是:

where t2.technical_value = 'XX' and t1.matnum = '60000000' and
      (matflag <> '50' or matflag is null)

【讨论】:

  • 你好 Gordon,我可能应该在这个问题中补充一点,我已经通过一个简单的 join 来工作 - 我只是对其他事情感兴趣,这对我帮助很大,谢谢!我将深入了解NULL-values,只是直到现在我才认为我需要它。
【解决方案2】:

在 SQL 中,NULL 表示“未知”值,因此对它的任何操作都会导致 NULL。试试COALESCE(t1.matflag, 0) &lt;&gt; 50...

【讨论】:

  • 谢谢,有趣的尝试!但是,我认为我会坚持 Gordons 的尝试,现在我知道为什么我的比较失败了。投了赞成票!
猜你喜欢
  • 2021-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-16
  • 1970-01-01
  • 2016-10-09
  • 2021-10-26
相关资源
最近更新 更多