如何从 SQL 查询中排除记录?
How to exclude records from SQL query?
给定以下 SQL 查询:
select t
from tableA t, tableA t2
where t.validAt = :validAt1 and t2.validAt = :validAt2
and t.uniqueId = t2.uniqueId
and nvl(t.code, 'xNVLx') != nvl(t2.code, 'xNVLx');
结果是我得到了 CODE 列值已更改的记录的记录。
到目前为止一切顺利。
例子:
更改:
CODE changed from 123 -> 456: IS IN RESULT SET, PERFECT
CODE changed from 123 -> NULL: IS IN RESULT SET, PERFECT
CODE changed from NULL -> 123: IS IN RESULT SET, PERFECT
无变化:
CODE changed from NULL -> NULL: NOT IN RESULT SET, PERFECT
CODE changed from 123 -> 123: NOT IN RESULT SET, PERFECT
现在要添加两个额外的特殊情况:
特殊情况:
Special Case 1: CODE changed from NULL -> 00: SHALL NOT BE RESULT SET
Special Case 2: CODE changed from NULL -> 01: SHALL NOT BE RESULT SET
问题: 有没有优雅简单的SQL exclude existing?
编辑:
我使用了@Plirkee 提出的解决方案:
and nvl( decode(t.code,
'00','xNVLx',
'01','xNVLx',
t.code),
'xNVLx')
!= nvl(
decode(t2.code,
'00','xNVLx',
'01','xNVLx',
t2.code),
'xNVLx')
但:从“00”到“01”的这种逻辑变化被视为有效,但不应该。
有什么想法吗?
您可以将您的逻辑实现为:
select . . .
from tableA t join
tableA t2
on t.validAt = :validAt1 and t2.validAt = :validAt2 and
t.uniqueId = t2.uniqueId
where t.code <> t2.code or (t.code is not null and t.code is null);
你可以使用decode
函数
select t
from tableA t, tableA t2
where t.validAt = :validAt1 and t2.validAt = :validAt2
and t.uniqueId = t2.uniqueId
and nvl(t.code, 'xNVLx') != nvl(decode(t2.code,'00','xNVLx','01','xNVLx',t2.code), 'xNVLx');
给定以下 SQL 查询:
select t
from tableA t, tableA t2
where t.validAt = :validAt1 and t2.validAt = :validAt2
and t.uniqueId = t2.uniqueId
and nvl(t.code, 'xNVLx') != nvl(t2.code, 'xNVLx');
结果是我得到了 CODE 列值已更改的记录的记录。 到目前为止一切顺利。
例子:
更改:
CODE changed from 123 -> 456: IS IN RESULT SET, PERFECT
CODE changed from 123 -> NULL: IS IN RESULT SET, PERFECT
CODE changed from NULL -> 123: IS IN RESULT SET, PERFECT
无变化:
CODE changed from NULL -> NULL: NOT IN RESULT SET, PERFECT
CODE changed from 123 -> 123: NOT IN RESULT SET, PERFECT
现在要添加两个额外的特殊情况:
特殊情况:
Special Case 1: CODE changed from NULL -> 00: SHALL NOT BE RESULT SET
Special Case 2: CODE changed from NULL -> 01: SHALL NOT BE RESULT SET
问题: 有没有优雅简单的SQL exclude existing?
编辑:
我使用了@Plirkee 提出的解决方案:
and nvl( decode(t.code,
'00','xNVLx',
'01','xNVLx',
t.code),
'xNVLx')
!= nvl(
decode(t2.code,
'00','xNVLx',
'01','xNVLx',
t2.code),
'xNVLx')
但:从“00”到“01”的这种逻辑变化被视为有效,但不应该。
有什么想法吗?
您可以将您的逻辑实现为:
select . . .
from tableA t join
tableA t2
on t.validAt = :validAt1 and t2.validAt = :validAt2 and
t.uniqueId = t2.uniqueId
where t.code <> t2.code or (t.code is not null and t.code is null);
你可以使用decode
函数
select t
from tableA t, tableA t2
where t.validAt = :validAt1 and t2.validAt = :validAt2
and t.uniqueId = t2.uniqueId
and nvl(t.code, 'xNVLx') != nvl(decode(t2.code,'00','xNVLx','01','xNVLx',t2.code), 'xNVLx');