首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

求 一语句,超级难解决方案

2012-02-10 
求 一语句,超级难表F1sntext1xin2xin15xin2表F2psnsnodesc12old23old134old256old367old488old599old6其中

求 一语句,超级难
表F1
sn   text
1     xin
2     xin1
5     xin2
表F2
psn     sno     desc
1           2         old
2           3         old1
3           4         old2
5           6         old3
6           7         old4
8           8         old5
9           9         old6
其中表F1.sn与F2.psn关联
F2的psn与   F2的   sno关联
要求:   查找出表F2中的记录,它的psn即不在表F1的sn中,同时也不与F2的sno关联:
具体就是  
    8       8     old5
    9       9   old6
这两个记录。
谢谢

[解决办法]
select * from F2 t
where not exists(select 1 from F1 where sn = t.psn)
and not exists(select 1 from F1, F2 where F1.sn = F2.psn and F2.psn = t.sno)
[解决办法]
--創建測試環境
Create Table F1
(sn Int,
[text] Varchar(10))
Insert F1 Select 1, 'xin '
Union All Select 2, 'xin1 '
Union All Select 5, 'xin2 '
Create Table F2
(psn Int,
sno Int,
[desc] Varchar(10))
Insert F2 Select 1, 2, 'old '
Union All Select 2, 3, 'old1 '
Union All Select 3, 4, 'old2 '
Union All Select 5, 6, 'old3 '
Union All Select 6, 7, 'old4 '
Union All Select 8, 8, 'old5 '
Union All Select 9, 9, 'old6 '
GO
--測試
Select
B.*
From
F2 B
Left Join
F1 A
On A.sn = B.psn
Where A.sn Is Null And B.psn = B.sno
GO
--刪除測試環境
Drop Table F1, F2
--結果
/*
psnsnodesc
88old5
99old6
*/
[解决办法]
/*你的思路值得我学习
呵呵,开始我没有想到
学习了学习了~~lz你的思路逻辑上游没有错误?指什么意思啊
不过我倒还是喜欢这样用*/
select * from f2 where psn not in
(select a.psn from f2 a inner join f2 b on a.psn=b.sno呀 ---用inner join
union
select psn from f2 join f1 on f1.sn=f2.psn)
[解决办法]
--***** 楼主给分把
--***** 楼主给分把
---------------------------------------
drop table f1,f2
create table f1
(sn int,
des nvarchar(50))

create table f2
(psn int,
sno int,
text1 nvarchar(50))

insert into f1 select 1, 'parent1 '
union select 10, 'parent2 '

insert into f2 select 1,2, 'child1 '
union select 2,3, 'child2 '
union select 3,4, 'child3 '
union select 8,8, 'child8 '
union select 9,9, 'child9 '
union select 10,11, 'child10 '
union select 11,12, 'child11 '
union select 12,13, 'child12 '
union select 13,14, 'child13 '
select s.* from (select * from f2 s where not exists (select 1 from f2 where sno=s.psn and s.psn <> psn )) s where s.psn not in(select sn from f1)

-----------结果
8 8child8
9 9child9

热点排行