left_join.md 1.5 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
    name varchar(256),
    post varchar(16)
)
```

Joe 想要列出所有的部门,如果这个部门有部门助理(post 为 `assistant`),则将 stuff 的名字也列出来,那么这个查询应该是:

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

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

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

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

fix bug  
张志晨 已提交
34
```sql
M
join  
Mars Liu 已提交
35 36 37 38 39 40 41 42 43 44
select d.id, d.name, e.name as assistant
from department as d
    left join employee as e on e.dept = d.id
where e.post = 'assistant'
```

## 选项

### A

fix bug  
张志晨 已提交
45
```sql
M
join  
Mars Liu 已提交
46 47 48 49 50 51 52 53
select d.id, d.name, e.name as assistant
from department as d
         cross join employee as e on e.dept = d.id
where e.post = 'assistant'
```

### B

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

### C

fix bug  
张志晨 已提交
63
```sql
M
join  
Mars Liu 已提交
64 65 66 67 68
select d.id, d.name, e.name as assistant
from department as d
         cross join employee as e on e.dept = d.id
where e.post = 'assistant'
```
L
luxin 已提交
69

M
join  
Mars Liu 已提交
70 71
### D

fix bug  
张志晨 已提交
72
```sql
M
join  
Mars Liu 已提交
73 74 75 76 77
select d.id, d.name, e.name as assistant
from employee as e
    left join department as d on e.dept = d.id
where e.post = 'assistant'
```