【转】数据库的左连接,右连接问题
转自 http://www.cnblogs.com/fanwenxuan/archive/2007/11/06/951473.html
前一阶段经历了几次程序员的面试,发现数据库这个部分占了很大的比重。而左连接,右连接又是很多人问的重点,当初我就是不太明白怎么一回事,所以吃了几次的亏。今天把专门作了一次关于左连接和右连接的文章,巩固一下知识:
要点:left join,right join,inner join
首先有如下两个表:
Student:
Quiz:
内连接:(inner join)包括连接表的匹配行
select Student.Name,Quiz.score from Quiz inner join Student on Student.ID=Quiz.ID
左连接:(left join)包括连接表匹配行以及左连接表的所有行
select Student.Name,Quiz.score from Student left join Quiz on Student.ID=Quiz.ID
右连接:(right join)结果包括连接表的匹配行以及右连接表的所有行
select Student.Name,Quiz.score from Student right join Quiz on Student.ID=Quiz.ID
当然,也可以看出左连接也可以写成右连接的形式:
select Student.Name,Quiz.score from Student right join Quiz on Student.ID=Quiz.ID等价于
select Student.Name,Quiz.score from Quiz left join Student on Student.ID=Quiz.ID
要点:left join,right join,inner join
首先有如下两个表:
Student:
| ID(int) | Name(nvarchar) |
| 1 | a |
| 2 | b |
| 3 | c |
| 4 | d |
| 5 |
e |
| 6 | f |
| ID(int) | score(int) |
| 1 | 60 |
| 2 | 70 |
| 4 | 80 |
| 6 | 90 |
| 8 | 100 |
| 9 | 30 |
select Student.Name,Quiz.score from Quiz inner join Student on Student.ID=Quiz.ID
| Name | score |
| a | 60 |
| b | 70 |
| d | 80 |
| f | 90 |
select Student.Name,Quiz.score from Student left join Quiz on Student.ID=Quiz.ID
| Name | score |
| a | 60 |
| b | 70 |
| c | null |
| d | 80 |
| e | null |
| f | 90 |
select Student.Name,Quiz.score from Student right join Quiz on Student.ID=Quiz.ID
| Name | score |
| a | 60 |
| b | 70 |
| d | 80 |
| f | 90 |
| null | 100 |
| null | 30 |
select Student.Name,Quiz.score from Student right join Quiz on Student.ID=Quiz.ID等价于
select Student.Name,Quiz.score from Quiz left join Student on Student.ID=Quiz.ID
努力不一定成功,但放弃一定失败!

浙公网安备 33010602011771号