MySQL 常见面试题 - 概念题
查询分析器中执行:
-- 建表 table1,table2:create table table1(idint,name varchar(10))
create table table2(idint,scoreint)
insertintotable1select1,'lee'
insertintotable1select2,'zhang'
insertintotable1select4,'wang'
insertintotable2select1,90
insertintotable2select2,100
insertintotable2select3,70
如表-------------------------------------------------
table1|table2|
-------------------------------------------------
id name|id score|
1lee|190|
2zhang|2100|
4wang|370|
-------------------------------------------------
以下均在查询分析器中执行
一, 外连接
1. 概念: 包括左向外联接, 右向外联接或完整外部联接
2. 左连接: left join 或 left outer join
(1) 左向外联接的结果集包括 LEFT OUTER 子句中指定的左表的所有行, 而不仅仅是联接列所匹配的行. 如果左表的某行在右表中没有匹配行, 则在相关联的结果集行中右表的所有选择列表列均为空值 (null).
(2)sql 语句
select * from table1 left join table2 on table1.id=table2.id
------------- 结果 -------------idnameidscore
------------------------------
1lee190
2zhang2100
4wangNULLNULL
------------------------------
注释: 包含 table1 的所有子句, 根据指定条件返回 table2 相应的字段, 不符合的以 null 显示
3. 右连接: right join 或 right outer join
(1) 右向外联接是左向外联接的反向联接. 将返回右表的所有行. 如果右表的某行在左表中没有匹配行, 则将为左表返回空值.
(2)sql 语句
select * from table1 right join table2 on table1.id=table2.id
------------- 结果 -------------idnameidscore
------------------------------
1lee190
2zhang2100
NULLNULL370
------------------------------
注释: 包含 table2 的所有子句, 根据指定条件返回 table1 相应的字段, 不符合的以 null 显示
4. 完整外部联接: full join 或 full outer join
(1) 完整外部联接返回左表和右表中的所有行. 当某行在另一个表中没有匹配行时, 则另一个表的选择列表列包含空值. 如果表之间有匹配行, 则整个结果集行包含基表的数据值.
(2)sql 语句
select * from table1 full join table2 on table1.id=table2.id
------------- 结果 -------------idnameidscore
------------------------------
1lee190
2zhang2100
4wangNULLNULL
NULLNULL370
------------------------------
注释: 返回左右连接的和 (见上左, 右连接)
二, 内连接
1. 概念: 内联接是用比较运算符比较要联接列的值的联接
2. 内连接: join 或 inner join
3.sql 语句
select * from table1 join table2 on table1.id=table2.id
------------- 结果 -------------idnameidscore
------------------------------
1lee190
2zhang2100
------------------------------
注释: 只返回符合条件的 table1 和 table2 的列
4. 等价 (与下列执行效果相同)A:selecta.*,b.*fromtable1 a,table2 bwherea.id=b.id
B:select*fromtable1 crossjointable2wheretable1.id=table2.id(注:crossjoin后加条件只能用where,不能用on)
三, 交叉连接 (完全)
1. 概念: 没有 WHERE 子句的交叉联接将产生联接所涉及的表的笛卡尔积. 第一个表的行数乘以第二个表的行数等于笛卡尔积结果集的大小.(table1 和 table2 交叉连接产生 3*3=9 条记录)
2. 交叉连接: cross join (不带条件 where...)
3.sql 语句
select * from table1 cross join table2
------------- 结果 -------------idnameidscore
------------------------------
1lee190
2zhang190
4wang190
1lee2100
2zhang2100
4wang2100
1lee370
2zhang370
4wang370
------------------------------
注释: 返回 3*3=9 条记录, 即笛卡尔积
4. 等价 (与下列执行效果相同)
A:select * from table1,table2
来源: http://www.bubuko.com/infodetail-2968590.html