---
title: "sql内 左右连接的例子"
author: "lyuno"
date: "2011-04-21T17:44:53Z"
tags: []
categories: ["数据库"]
slug: "sql"
draft: false
lastmod: "2011-04-21T21:35:52Z"
id: 1011531
url: "https://lyuno.iteye.com/blog/1011531"
---

弄个例题，直观一点。两个表：
--表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
stu.id   exam.id  name     grade
--------------------------------
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