left_join.md 1.2 KB
Newer Older
M
join  
Mars Liu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 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
# 左连接

现有部门表

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

和员工表

```mysql
create table employee(
    id int primary key auto_increment,
    dept int,
    name varchar(256),
    post varchar(16)
)
```

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

## 答案

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