日期:2014-05-19  浏览次数:20774 次

求 一语句,超级难
表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
--結果
/*
psn sno desc
8 8 old5
9 9 old6
*/
------解决方案--------------------
/*你的思路值得我学习
呵呵,开始我没有想到
学习了学习了~~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 8 child8
9 9 child9