`
xiangxingchina
  • 浏览: 508408 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Mysql 各种连接查询详解

    博客分类:
  • db
 
阅读更多

一、外连接
概念:包括坐向外连接、右向外连接和完整外部连接。
1. 左连接:left join 或 left outer join
(1)左外连接的结果集包括 LEFT JOIN 子句中指定的左表的所有行,而不仅仅是连接列所匹配的行。如果左表的某行在右表中没有匹配行,则在相关联的结果集行中右表的所有选择列表列均为空值(null)。
(2)SQL语句:select * from table1 left join table2 on table1.id = table2.id;
2. 右连接:right join 或 right outer join
(1)右外连接的结果集包括 RIGHT JOIN 子句中指定的右表的所有行,而不仅仅是连接列所匹配的行。如果右表的某行在左表中没有匹配行,则在相关联的结果集行中左表的所有选择列表列均为空值(null)。
(2)SQL语句:select * from table1 right join table2 on table1.id = table2.id;
3. 完整外部连接:full join 或 full outer join
(1)完整外部连接返回左表和右表的所有行。当某行在另外一个表中没有匹配行时,则另一个表的选择列表列包含空值。如果表之间有匹配行,则整个结果集行包含基表的数据值
(2)SQL语句:select * from table1 full join table2 on table1.id = table2.id;

二、内连接
概念:内连接是用比较运算符比较要连接列的值的连接
1. 内连接:join 或 inner join
(1)内连接只返回符合条件的table1和table2的列
(2)SQL语句:select * from table1 join table2 on table1.id = table2.id;
(3)内连接等价于(与这个SQL执行效果相同)SQL:select * from table1 a,table2 b where a.id = b.id;
(4)内连接也等价于(与这个SQL执行效果相同)SQL:select * from table1 cross join table2 where table1.id = table2.id(注:cross join 后加条件只能用where不能用on)

三、交叉连接
概念:没有where子句的交叉连接将产生连接所涉及的表的笛卡尔积。第一个表的行数乘以第二个表的行数等于笛卡尔积结果集的大小。(table1 和 table2 交叉连接产生3*3 = 9条记录)
1. 交叉连接:cross join(不带条件where)
(1)SQL语句:select * from table1 cross join table2;
(2)交叉连接等价于(与这个SQL执行效果相同)SQL:select * from table1,table2;

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics