所以,我有一个简单的 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”。
现在,如果我更改 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/