码迷,mamicode.com
首页 > 其他好文 > 详细

连接查询

时间:2015-06-02 19:31:37      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:

连接查询:列的扩展
1. 等值连接查询 (内连接)
笛卡尔积
join on

2. 外连接(left.right.full)

left左连接:
left 左边表为主表 ,右边的为从表,显示的结果集以主表为主
如果从表中没有和它匹配的数据,就以NULL值填充

right右连接:
right 右边的表为主表

full 全连接
每个表都完全显示,互相匹配数据,如果对方没有则以NULL填充

联合查询:行的扩展

用Union将两个查询联合起来显示,追加行的形式在结果集中显示
必须保证两个查询结果的列的格式是一样的

SELECT * FROM Info
SELECT * FROM Nation
SELECT * FROM Family

select Info.Code,Info.Name,Nation.Name from Info,Nation where Nation.Code = Info.Nation

SELECT Info.Code,Info.Name,Nation.Name,Family.Name from Info JOIN Nation on Nation.Code = Info.Nation JOIN Family on Info.Code=Family.InfoCode

SELECT Info.Code,Info.Name,Nation.Name from Info right JOIN Nation on Nation.Code = Info.Nation

SELECT Info.Code,Info.Name,Nation.Name from Info full JOIN Nation on Nation.Code = Info.Nation


SELECT Code,Name from Info
UNION
SELECT code,Name from Nation


无关子查询

查询嵌套,外层查询成为主查询,内层查询成为子查询
子查询的结果成为主查询的条件

例子:查INFO表中和学号为‘p005’的学生出生年份一样的学生信息
select * FROM Info where YEAR(Birthday)=(SELECT YEAR(Birthday) from Info where Code = ‘p005‘)

分页
SELECT top 5 * from News where ids NOT IN (SELECT top 5 ids from News)

查成绩超过学号为105的同学的所有成绩的成绩表

SELECT * FROM score where degree>ANY(SELECT degree from score where sno=‘105‘)

相关子查询

需要依赖于外层查询

外层查询和子查询存在联系

例子:查询计算机系与电子工程系不同职称的教师

SELECT * FROM teacher t1 where depart=‘计算机系‘ AND NOT EXISTS(
SELECT * FROM teacher t2 WHERE t2.depart=‘电子工程系‘ AND t1.prof = t2.prof
)
UNION
SELECT * FROM teacher t1 where depart=‘电子工程系‘ AND NOT EXISTS(
SELECT * FROM teacher t2 WHERE t2.depart=‘计算机系‘ AND t1.prof = t2.prof)

连接查询

标签:

原文地址:http://www.cnblogs.com/languang/p/4547141.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!