Mysql之inner join,left join,right join详解 内外连接

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

文章分类:PHP编程

首先借用官方的解释下:

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

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

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

比如我们有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代码 复制代码
  1. SELECT  *  FROM  `xs`  LEFT   JOIN  `cj`  ON  xs.id = cj.id    
 

返回

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

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

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

 

Sql代码 复制代码
  1. 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还有另外一种写法,两者是等价的,都是等值连接

 

Sql代码 复制代码
  1. SELECT  *  FROM  `xs`,`cj`  WHERE  xs.id = cj.id   


首先说 内外连接:
  内连接:取的两个表的(有能连接的字段),的交集,即字段相同的。利用内连接可获取两表的公共部分的记录,
      select * from A,B where A.Aid=B.Bnameid
   与 Select * from A JOIN B ON A.Aid=B.Bnameid的运行结果是一样的。
  外连接:左右连接。

你可能感兴趣的:(sql,编程,mysql,PHP)