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
select d.id, d.name, e.name as assistant
from department as d
37 38 39 40 41
         left join (select name, dept_id
                    from employee
                    where post='assistant') as e on e.dept_id = d.id


M
join  
Mars Liu 已提交
42 43 44 45 46 47
```

## 选项

### A

fix bug  
张志晨 已提交
48
```sql
M
join  
Mars Liu 已提交
49 50 51 52 53 54 55 56
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  
张志晨 已提交
57
```sql
M
join  
Mars Liu 已提交
58 59 60 61 62 63 64 65
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  
张志晨 已提交
66
```sql
M
join  
Mars Liu 已提交
67 68 69 70 71
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 已提交
72

M
join  
Mars Liu 已提交
73 74
### D

fix bug  
张志晨 已提交
75
```sql
M
join  
Mars Liu 已提交
76 77 78 79 80
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'
```