- 我的电脑系统:Windows 10 64位
- SQL Server 软件版本: SQL Server 2014 Express
本篇博客里面使用了
scott
库,如何你现在还没有添加这个库到你的服务器里面,请在查看本篇博客前,访问这篇博文来在你的服务器里面附加scott
库。
连接查询
定义:
将两个表或者两个以上的表以一定的连接条件连接起来。从中检索出满足条件的数据。
一 . 内连接 — 知识点 (重点中的重点)
牛刀小试
select "E".ename "员工姓名", "D".dname "部门名称"
from emp "E"
join dept "D"
on "E".deptno = "D".deptno
需要学的知识点:
select ... from A, B
的用法select ... from A, B where ...
的用法select ... from A join B on ...
的用法select ... from A, B where ...
与select ... from A join B on ...
的比较select
、from
、where
、join
、on
、group
、order
、top
、having
的混合使用。
1 . select ... from A, B
的用法 — 笛卡尔积
--emp是14行; dept是5行3列
select * from emp, dept
--输出是70行。不任何条件,进行笛卡尔积连接。
A
表里面没有个元组都会连接 B
表一个元组,这样就导致 B
表中的每一个元组都连接了 A
表中的没有个元组。
产生的结果: 行数是 A和B的乘积;列数是A和B之和。或者说:把A表的每一条记录都和B表的每一条记录组合在一起,形成的是个笛卡尔积。
2 . select ... from A, B where ...
的用法
select *
from emp, dept
where empno = 7369
--输出5行,11列
其中有两个列
deptno
属性,一列是来自dept
表,一列是来自emp
表。
select ... from A, B where ...
中的 where
是对 select * from emp, dept
产生的dept
和 emp
两个表进行笛卡尔积后得到的临时表进行过滤。
注意:
select * from emp, dept where 1-1
输出70行 11列
select * from emp, dept where empno = 7369
5行
select * from emp, dept where deptno = 10
error
select * from emp, dept where emp.deptno = 10
5行的倍数
select * from emp, dept where dept.deptno = 10
14行
3 . select ... from A join B on ...
的用法
select "E".ename "员工姓名", "D".dname "部门名称"
from emp "E" --"E" 是别名
join dept "D" --"D" 是别名 join是连接
on "E".deptno = "D".deptno ---on 表示:连接条件
--连接条件是:两个表里面的deptno属性相同,才能连接
--所以现在得到的结果不是70行。
select *
from emp "E"
join dept "D"
on "E".deptno = "D".deptno
--输出是11列(有两列(deptno)是重复的)
下面的两个指令输出都是一样的结果。
select "E".ename "员工姓名", "D".dname "部门名称"
from emp "E"
join dept "D"
on 1=1 --连接条件是 1=1 表示永远为真,所以执行后得到的结果是70行2列。
select "E".ename "员工姓名", "D".dname "部门名称"
f