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

◆求一SQL语句
有两张表:

表一(fatherid为0时为大类,不为零时就是大类的ID号,如计算机系的Fatherid为100,则是属于ID为“100”理工学院的子类.

id         fatherid     name
100             0             理工学院
101           100           计算机系
102           100           机电工程系
103           100           生物工程系
104             0             人文学院
105           104           音乐系
106           104           法律系
....................
....................

表二的sortid号则是根据表一的ID号得到的,如张三的srotid为101
则说明,张三是表一中ID号为101的计算机系.

表二
id           sortid           name
1               101               张三
2               101               李四
3               101               王五
4               102               刘六


现在需要用一个SQL语句,求出如下结果:(因为表一中id为101、102,在表二中都有相关的数据,所以要显示出来,反之则不要显示)
id         fatherid     name
100             0             理工学院
101           100           计算机系
102           100           机电工程系


谢谢各位。。



------解决方案--------------------
select * from 表一 a where exists(select 1 from 表二 where a.id=id )
------解决方案--------------------
select * from 表一 where id in(select distinct id from 表二) union all select * from 表一 where fatherid = 0
------解决方案--------------------
select id,fatherid,name from table1
where id in (select distinct sortid from table2 union all select fatherid from table1 where id in (select distinct sortid from table2))
------解决方案--------------------
第一条语句好象不是你要的结果吧?
exists: 存在的关系 它不返回结果集,只返回TRUE FALSE
------解决方案--------------------
exists 存在!
比如:
select a.* from a,b
where a.pkid = b.pkid

可以用下面来替代:
select * from a
where exists(select ' ' from b where a.pikid = b.pkid)

用exists有时的效率会比连接高。