Home > Database > Mysql Tutorial > 详解mysql语法left join,right join,inner join_MySQL

详解mysql语法left join,right join,inner join_MySQL

WBOY
Release: 2016-06-01 13:35:46
Original
785 people have browsed it

bitsCN.com

详解mysql语法left join,right join,inner join
 

测试表用户表user:

详解mysql语法left join,right join,inner join_MySQL

测试表密码表pwd:

详解mysql语法left join,right join,inner join_MySQL

1、创建user表:

1

CREATE TABLE `user` (

2

  `id` int(11) NOT NULL auto_increment,

3

  `name` varchar(255) default NULL,

4

  `password` varchar(255) default NULL,

5

  PRIMARY KEY  (`id`)

6

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2、创建pwd表:

1

CREATE TABLE `pwd` (

2

  `id` int(11) NOT NULL auto_increment,

3

  `userid` int(11) default NULL,

4

  `passwd` varchar(255) default NULL,

5

  PRIMARY KEY  (`id`)

6

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

 

3、使用inner join 将pwd表中的passwd填入到user表中的password列(根据userid),SQL语句:

1

UPDATE `user` U

2

INNER JOIN `pwd` P

3

ON P.userid=U.id

4

SET U.password = P.passwd;

4、 left join(左联接) 查询user中的信息

 

1

SELECT us.*,pw.* FROM `user` us 

2

LEFT JOIN pwd pw

3

ON pw.userid=us.id;

 

 

结果:

详解mysql语法left join,right join,inner join_MySQL

说明: 
left join是以User表的记录为基础的,User可以看成左表,pwd可以看成右表,left join是以左表为准的. 
换句话说,左表(User)的记录将会全部表示出来,而右表(pwd)只会显示符合搜索条件的记录(例子中为: pw.userid=us.id). 
B表记录不足的地方均为NULL. 

5、left join(左联接) 查询pwd中的信息


1

SELECT us.*,pw.* FROM `user` us 

2

RIGHT JOIN pwd pw

3

ON pw.userid=us.id;

 

结果:

详解mysql语法left join,right join,inner join_MySQL

说明:

和left join的结果刚好相反,这次是以右表(pwd)为基础的,user表不足的地方用NULL填充. 

6、inner join(相等联接或内联接) 

1

SELECT us.*,pw.* FROM `user` us 

2

inner JOIN pwd pw

3

ON pw.userid=us.id;

 

结果:

详解mysql语法left join,right join,inner join_MySQL

说明:

很明显,这里只显示出了 pw.userid=us.id的记录.这说明inner join并不以谁为基础,它只显示符合条件的记录. 

 

bitsCN.com
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template