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

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

fix bug  
张志晨 已提交
5
```sql
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
    name varchar(256),
    post varchar(16)
)
```

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

M
Mars Liu 已提交
17 18
<hr/>

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

F
feilong 已提交
21 22
* `show databases;` 列出所有数据库
* `show tables;` 列出所有表
M
Mars Liu 已提交
23

M
Mars Liu 已提交
24 25
## 答案

fix bug  
张志晨 已提交
26
```sql
M
Mars Liu 已提交
27 28 29 30 31 32 33 34 35 36 37
select distinct(dept)                  as dept,
               (select count(*)
                from employee as i
                where i.dept = o.dept) as emp
from employee as o;
```

## 选项

### A

fix bug  
张志晨 已提交
38
```sql
M
Mars Liu 已提交
39 40 41 42 43 44 45 46
select distinct(dept)               as dept,
               (select count(*)
                from employee as i) as emp
from employee as o;
```

### B

fix bug  
张志晨 已提交
47
```sql
M
Mars Liu 已提交
48 49 50 51 52 53 54 55 56
select distinct(dept)              as dept,
               (select count(*)
                from employee
                where dept = dept) as emp
from employee
```

### C

fix bug  
张志晨 已提交
57
```sql
M
Mars Liu 已提交
58 59 60 61
select dept                    as dept,
       (select count(*)
        from employee as i
        where i.dept = o.dept) as emp
M
Mars Liu 已提交
62 63
from employee as o
```