首页 > 技术文章 > 数据库之子查询二(相关子查询)

SoulReaper 2013-09-09 14:26 原文

四、相关子查询(exists,not exists)
    通过子查询的反复执行逐一查询每一行,从而确定内容是否满足条件(返回值为true或者false),从而决定是否显示外查询内容(可以是同一数据表或者不同数据表)
    和连接查询功能基本一样,但是实现方式不一样,连接查询适合查询循环次数过多的时候
    个人觉得连接查询比较好用
    格式: select 表1.字段1.......
                from 表1
                where exists
                (
                select *
                from 表2
                where
                表1.字段1=表2.字段1
                and.........    
                )
    
举例:
1.相关子查询
select s.stuID,s.stuName,s.age,s.sex,s.birth
from tstudent s
where exists
(
select *
from tresult t
where s.stuID=t.StuID
and t.curID='t105'
)
2.内连接查询:
select s.stuID,s.stuName,s.age,s.sex,s.birth
from tstudent s,tresult t
where s.stuID=t.stuID
and t.curID='t105'
3.using优化内连接查询
select s.stuID,s.stuName,s.age,s.sex,s.birth
from tstudent s join tresult t
using (`stuID`)
where t.curID='t105'
4.on形式内连接查询
select s.stuID,s.stuName,s.age,s.sex,s.birth
from tstudent s join tresult t
on s.stuID=t.stuID
where t.curID='t105'
以上四种结果相同
5.not exists返回为无结果时为true,显示结果
例子:
select s.stuID,s.stuName,s.age,s.sex,s.birth
from tstudent s
where not exists
(
select *
from tresult t
where s.stuID=t.StuID
and t.curID='t105'
)

推荐阅读