Mysql之inner join,left join,right join, full join, inner join详解

时间: 2011-03-23  分类: php+Mysql  收藏

inner join(等值连接):只返回两个表中联结字段相等的行;

left join(左联接):返回包括左表中的所有记录和右表中联结字段相等的记录;

right join(右联接):返回包括右表中的所有记录和左表中联结字段相等的记录。

inner join:只返回符合条件的table1和table2的列

full join:返回所有列 左边在右边没有的补null 右边在左边没有的也补null

 

比如我们有xs、cj两个表

xs表                                 cj表

---------------                  ----------------------

id     name                     id      score

1      张三                      1       96

2      李四                      2       80

                                 3       86

 

Sql代码

1        SELECT *FROM `xs`INNER JOIN `cj` ON xs.id = cj.id    

返回

------------------------

id   name   id  score
1   张三   1   96
2   李四   2   80

-----------------------

 

Sql代码

2        SELECT *FROM `xs` LEFT JOIN `cj` ON xs.id = cj.id   

返回

------------------------

id   name   id  score
1   张三   1   96
2   李四   2   80

-----------------------

 

Sql代码

3        SELECT *FROM `xs` RIGHT JOIN `cj` ON xs.id = cj.id   

返回

id       name    id   score
1       张三      1     96
2       李四      2     80
NULL    NULL  3     86

 

其中还有inner join还有另外一种写法,两者是等价的,都是等值连接

 

SELECT * FROM`xs`,`cj` WHERE xs.id = cj.id

 

select * from table1 full join table2 ontable1.id=table2.id
-------------结果-------------
id         name         id        score
------------------------------
1           ee            1          90
2           zhang        2       100
4           wang        NULL  NULL
NULL     NULL        3        70
------------------------------
注释:返回左右连接的和(见上左、右连接)

分享到:

评论

昵 称: