left_join.md 1.5 KB
Newer Older
M
join  
Mars Liu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# 左连接

现有部门表

```mysql
create table department(
    id int primary key auto_increment,
    name varchar(256)
)
```

和员工表

```mysql
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/>

M
Mars Liu 已提交
27
点击进入[MySQL实战练习环境](https://mydev.csdn.net/product/pod/new?image=cimg-centos7-skilltreemysql&connect=auto&create=auto&utm_source=skill)
M
Mars Liu 已提交
28 29
* `show databases` 列出所有数据库
* `show tables` 列出所有表
M
Mars Liu 已提交
30

M
join  
Mars Liu 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
## 答案

```mysql
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

```mysql
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

```mysql
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

```mysql
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'
```
 
### D

```mysql
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'
```