Help, 关于not exists的应用

[复制链接]
查看11 | 回复9 | 2015-3-6 11:58:18 | 显示全部楼层 |阅读模式
我有一个test001表如下:
select * from test001;
Row#
回复

使用道具 举报

千问 | 2015-3-6 11:58:18 | 显示全部楼层
我不太知道这个pub币怎样用,好像有一百来个,悬赏一个会不会没有人答?不太懂怎样修改,请不吝赐教。谢谢
回复

使用道具 举报

千问 | 2015-3-6 11:58:18 | 显示全部楼层
试着理解下:
not esists(..
AND TRUNC(x.effective_start_date) > t1.effective_start_date
)
x是where中的表,t1是主表
不存在x.effective_start_date) > t1.effective_start_date,实际找的就是t1.effective_start_date最大的那条
回复

使用道具 举报

千问 | 2015-3-6 11:58:18 | 显示全部楼层
正解。
test001表中,person_id相同的各记录中,不存在某条记录的effective_start_date大于另一条记录的effective_start_date。即,取effective_start_date最大的那条记录。
回复

使用道具 举报

千问 | 2015-3-6 11:58:18 | 显示全部楼层
SQL> create table test_tab
2(
3c1 nvarchar2(10),
4c2 date
5)
6;

Table created

SQL> insert into test_tab select 1,sysdate from dual;

1 row inserted

SQL> insert into test_tab select 2,sysdate from dual;

1 row inserted

SQL> insert into test_tab select 3,sysdate from dual;

1 row inserted

SQL> insert into test_tab select 4,sysdate from dual;

1 row inserted

SQL> commit;

Commit complete

SQL> select * FROM test_tabt1 where
2NOT EXISTS ( SELECT 'x' FROM test_tab x
3
WHERE t1.c1 = x.c1
4
AND TRUNC(x.c2) > x.c2);

C1
C2
------------------------------ -----------
1
2009/4/4 16
4
2009/4/4 16
3
2009/4/4 16
2
2009/4/4 16

SQL>
回复

使用道具 举报

千问 | 2015-3-6 11:58:18 | 显示全部楼层
Oracle Database 10g Enterprise Edition Release 10.2.0.2.0

楼主的是什么版本?
回复

使用道具 举报

千问 | 2015-3-6 11:58:18 | 显示全部楼层
SQL> insert into test_tab select 1,sysdate from dual;

1 row inserted

SQL> commit;

Commit complete

SQL>
SQL> select * FROM test_tabt1 where
2NOT EXISTS ( SELECT 'x' FROM test_tab x
3
WHERE t1.c1 = x.c1
4
AND TRUNC(x.c2) > x.c2);

C1
C2
------------------------------ -----------
1
2009/4/4 16
1
2009/4/4 16
4
2009/4/4 16
3
2009/4/4 16
2
2009/4/4 16

SQL>
回复

使用道具 举报

千问 | 2015-3-6 11:58:18 | 显示全部楼层
谢谢HelloWorld_001和 y711
我也认可不存在x.effective_start_date) > t1.effective_start_date,但是我没法理解为什么结论就是“实际找的就是t1.effective_start_date最大的那条”???虽然实际确实如你所说
按理说子集应该是返回PERSON_ID=111中最小那条(第四条)真值。然后整个not exists SQL才返回最后的那3条。
但是子集返回第四条的原理没法懂。
我知道实际上(从结果看来)是找最大那条。但是执行流程不明
回复

使用道具 举报

千问 | 2015-3-6 11:58:18 | 显示全部楼层
谢谢zhpsam
你的测试中‘AND TRUNC(x.c2) > x.c2’写错了,请写成‘AND TRUNC(x.c2) > t1.c2’跑一遍。谢谢
回复

使用道具 举报

千问 | 2015-3-6 11:58:18 | 显示全部楼层
TO zhpsam
估计把日期弄臣不同date估计才更清楚
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行