首页 > 其他 > 详细

多表查询

时间:2020-05-24 12:42:00      阅读:36      评论:0      收藏:0      [点我收藏+]

多表查询:联接查询、子查询、集合运算

 

 

联接查询

交叉联接:笛卡尔积

select * from <表1>,<表2>

 

内联接:有条件的联接

select * from <表1> inner join <表2> on <条件> --SQL
select * from <表1>,<表2> where <条件>          --T-SQL
--条件一般为 A=B
--不满足条件的两表里的数据全部删除

外连接:保留 舍弃的记录

select * from <表1> left/right join <表2> on <条件> where <条件>--SQL
--where是对联接后的表进行条件筛选
--left join保留左侧表1中没有联接上的数据
--right join保留右侧表2中没有联接上的数据

自连接:表与自身联接

select * from <表1>[as] 别名, <表2>[as] 别名  where <条件>

 

 

子查询(嵌套查询)

不相关查询:子查询条件不依赖于主查询,先执行子查询再执行主查询

select sname from s where sage=(
select sage from s sname =小明
)
--查找s表中与小明同年龄的人的姓名
--子查询可以独立存在,所以为不相关子查询

select sname from s where sage in (
select sage from s sname =小明
)
--多值时不能使用= 要用 in/not in

 

相关子查询:子查询条件依赖于主查询

select sname from s exists (
select * from sc where cno=2 and s,sno=sc.sno
)

--相关循环的联接使用exists
--查询选修了2号课程的学生的姓名
--依次遍历外查询的表中的数据,将数据带入到内查询的表中,判断是否能找到满足内查询条件的记录
--若能找到满足条件的记录,则返回为真,否则为假
--no exists 表示不存在的为真

 

select(子查询)

from(子查询)

where(子查询)

 

集合查询

并 R union S 

select * fromwhere 条件 union select * fromwhere 条件 

 

交 R intersect S

select * fromwhere 条件 intersect select * fromwhere 条件 

 

差 R except S

select * fromwhere 条件 except select * fromwhere 条件 

 

集合查询不是所有集合都可以使用

 

多表查询

原文:https://www.cnblogs.com/yrxc/p/12950367.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!