in_column.md 1.0 KB
Newer Older
M
Mars Liu 已提交
1 2 3 4 5
# 列子查询

Joe 打算写一个查询,根据员工表

```mysql
M
Mars Liu 已提交
6 7 8
create table employee
(
    id   int primary key auto_increment,
M
Mars Liu 已提交
9
    dept varchar(64),
M
Mars Liu 已提交
10 11 12 13 14 15 16 17 18 19
    name varchar(256),
    post varchar(16)
)
```

统计每个部门的人数,但是他不打算用 group by。那么还可以怎做?

## 答案

```mysql
M
Mars Liu 已提交
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
select distinct(dept)                  as dept,
               (select count(*)
                from employee as i
                where i.dept = o.dept) as emp
from employee as o;
```

## 选项

### A

```mysql
select distinct(dept)               as dept,
               (select count(*)
                from employee as i) as emp
from employee as o;
```

### B

```mysql
select distinct(dept)              as dept,
               (select count(*)
                from employee
                where dept = dept) as emp
from employee
```

### C

```mysql
select dept                    as dept,
       (select count(*)
        from employee as i
        where i.dept = o.dept) as emp
M
Mars Liu 已提交
55 56
from employee as o
```