---
title: "mysql 内连接和外连接"
author: "lynneahui"
date: "2010-07-05T21:03:37Z"
tags: [".net", "Blog", "HTML", "MySQL", "面试"]
categories: ["数据库"]
slug: "mysql"
draft: false
lastmod: "2010-07-05T21:03:37Z"
id: 706147
url: "https://lynneahui.iteye.com/blog/706147"
---

转自：http://blog.chinaunix.net/u3/90025/showart_1769183.html

面试的时候被问到mysql的内连接和外连接，很久没接触了，上网查了一下，特此转来一篇好的博文分享。
/×------------------------------------------------------------×/
弄个例题，直观一点。两个表： 
--表stu 
id name 
1, Jack 
2, Tom 
3, Kity 
4, nono 
--表exam 
id grade 
1, 56 
2, 76 
11, 89 

内连接 （显示两表id匹配的） 
select stu.id,exam.id,stu.name, exam.grade from stu inner join exam on stu.id=exam.id 

-------------------------------- 
1 1 Jack 56 
2 2 Tom 76 


左连接（显示join 左边的表的所有数据，exam只有两条记录，所以stu.id,grade 都用NULL 显示） 
select stu.id,exam.id,stu.name, exam.grade from stu left join exam on stu.id=exam.id 
1 1 Jack 56 
2 2 Tom 76 
3 NULL Kity NULL 
4 NULL nono NULL 

右连接（与作连接相反，显示join右边表的所有数据） 
select stu.id,exam.id,stu.name, exam.grade from stu right join exam on stu.id=exam.id 
1 1 Jack 56 
2 2 Tom 76 
NULL 11 NULL 89

总结来说：
内连接取两个表的交集，外连接分左和右，左连接取左边的全部，右连接取右边的全部。
内连接:进行连接的两个表对应的相匹配的字段完全相同的连接。
左连接：LEFT OUTER JOIN， 两个表左连接时会返回左边表中的所有行和右边表中与之相匹配的列值，如果没有则用空值代替。
右连接：RIGHT OUTER JOIN，两个表进行右连接时会返回右边表中的所有的行和左边表中与之相匹配的列值没有相匹配的用控制代替。
