内连接1 语法select
from 表1
inner join 表2 on 表1.列名 条件运算符 表2.列名
[where 条件]
[order by 排序列]
其中“on 表1.列名 条件运算符 表2.列名” 中,条件运算符常用的是:=、。
表1.列名和表2.列名,分别是两个表的公共列。
内连接查询出的是两个表公共列共有的记录。
2 示例(1)books与authors内连接sql语句
select b.bookcode as 图书编号, b.bookname as 图书名称, a.authorname as 作者姓名from books as binner join authors as a on b.authorid = a.authorid
(2)内连接另外一种写法
sql server2005还兼容以前版本的内连接语法,即使用where子句进行内连接。 select b.bookcode as 图书编号, b.bookname as 图书名称, a.authorname as 作者姓名from books b, authors awhere b.authorid = a.authorid
3 多表内连接语法select
from 表1
inner join 表2 on 表1.列名 条件运算符 表2.列名
inner join 表3 on 表1.列名 条件运算符 表3.列名
……
[where 条件]
[order by 排序列]
4 示例
select b.bookcode as 图书编号, c.publishername as 出版商名, b.bookname as 图书名称,a.authorname as 作者姓名from books b inner join authors a on b.authorid=a.authorid inner join publisher c on b.publisherid=c.publisherid
外连接左外连接语法select
from 左表
left [outer] join 右表 on 左表.列名 条件运算符 右表.列名
[where 条件]
[order by 排序列]
示例使用左外连接查询books与authors表中的数据
select b.bookcode as 图书编号, b.bookname as 图书名称, a.authorname as 作者姓名from books b left join authors a on b.authorid=a.authorid
左外连接是以左表为主表,去关联右表(从表),结果集中包含主表所有数据行,如果主表的某行在从表中没有匹配行时,则从表的选择列为null值。
右外连接语法select
from 左表 right [outer] join 右表
on 左表.列名 条件运算符 右表.列名
[where 条件]
[order by 排序列]
示例使用右外连接查询books与authors表中的数据
select b.bookcode as 图书编号, b.bookname as 图书名称, a.authorname as 作者姓名
from books b
right join authors a on b.authorid=a.authorid
右外连接是以右表为主表,去关联左表(从表),结果集中包含主表所有数据行,如果主表的某行在从表中没有匹配行时,则从表的选择列为null值。
完全连接 语法 select
from 左表
full [outer] join 右表 on 左表.列名 条件运算符 右表.列名
[where 条件]
[order by 排序列]
完全连接左表和右表中所有行,当某行数据在另一个表中没有匹配时,则另一个表的选择列值为null
示例使用完全连接查询books与authors表中的数据
select b.bookcode as 图书编号, b.bookname as 图书名称, a.authorname as 作者姓名from books b full join authors a on b.authorid=a.authorid
交叉联接
概念:没有用where子句的交叉连接将产生连接所涉及的笛卡尔积第一个表的行数乘以第二个表的行数等于笛卡尔积和结果集的大小
交叉连接: cross join(不带条件where,如果带返回或显示的是匹配的行数)
sql语法:select * from books cross join books
如果有条件(where)select * from books cross join authors where books.authorid= authors.authorid等价于select * from books ,authors --(不带where)
