right_join.md 1.4 KB
Newer Older
M
join  
Mars Liu 已提交
1 2 3 4
# 右连接

现有部门表

fix bug  
张志晨 已提交
5
```sql
M
join  
Mars Liu 已提交
6 7 8 9 10 11 12 13
create table department(
    id int primary key auto_increment,
    name varchar(256)
)
```

和员工表

fix bug  
张志晨 已提交
14
```sql
M
join  
Mars Liu 已提交
15 16
create table employee(
    id int primary key auto_increment,
M
Mars Liu 已提交
17
    dept_id int,
M
join  
Mars Liu 已提交
18 19 20 21 22 23 24 25
    name varchar(256),
    post varchar(16)
)
```

公司经过了一轮调整后,员工信息有些混乱,现在 Joe 要写一个查询,找出部门信息写
错的员工,这些员工所在的部门在 department 表中没有对应记录。

M
Mars Liu 已提交
26 27
<hr/>

F
feilong 已提交
28
点击进入[MySQL实战练习环境](https://mydev.csdn.net/product/pod/new?image=cimg-centos7-skilltreemysql&connect=auto&create=auto&utm_source=skill){target="_blank"}。
F
feilong 已提交
29

F
feilong 已提交
30 31
* `show databases;` 列出所有数据库
* `show tables;` 列出所有表
M
Mars Liu 已提交
32

M
join  
Mars Liu 已提交
33 34
## 答案

fix bug  
张志晨 已提交
35
```sql
M
join  
Mars Liu 已提交
36 37 38 39 40 41 42 43 44 45
select e.id, e.name, e.dept
from department as d
    right join employee as e on d.id = e.dept
where d.id is null;
```

## 选项

### A

fix bug  
张志晨 已提交
46
```sql
M
join  
Mars Liu 已提交
47 48
select e.id, e.name, e.dept
from employee as e
49
    right join department as d on d.id = e.dept
M
join  
Mars Liu 已提交
50 51 52 53 54
where e.id is null;
```

### B

fix bug  
张志晨 已提交
55
```sql
M
join  
Mars Liu 已提交
56 57
select e.id, e.name, e.dept
from employee as e
58
     right join department as d on d.id = e.dept
M
join  
Mars Liu 已提交
59 60 61 62 63
where d.id is null;
```

### C

fix bug  
张志晨 已提交
64
```sql
M
join  
Mars Liu 已提交
65 66 67 68 69 70 71 72 73
select e.id, e.name, e.dept
from department as d
    join employee as e on d.id = e.dept
where d.id is null;
```


### D

fix bug  
张志晨 已提交
74
```sql
M
join  
Mars Liu 已提交
75 76 77 78 79
select e.id, e.name, e.dept
from department as d
    right join employee as e on d.id = e.dept
where d.id is null;
```