SQL 不返回正确的值

标签 sql oracle11g

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

查询基本上是 select from table1table2上有一个子查询其中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”。 现在,如果我更改 and t1.matflag != '50' 中的 where 子句至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 位生产版。

最佳答案

了解如何使用正确的显式 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)

关于SQL 不返回正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49281563/

相关文章:

php - 您的 SQL 语法 PHP MySQL 有错误

java - Liquibase:使用序列

sql - 将总值的部分计算为每行的列数(数据透视表)

SQL Server 数据库名称引用

mysql - 如何从两个不同的表计算(数量*价格)的总和?

sql - postgresql 触发可能的无限循环?

PHP 表单似乎并不总是写入数据库

sql - 一条语句中的多个游标

mysql - Oracle 的 group by 和 count 查询问题

oracle - 生成数