DoubleNotExists.md 1.8 KB
Newer Older
M
Mars Liu 已提交
1 2
# Double Not Exists Check

M
typo  
Mars Liu 已提交
3
风控部门的数据库中有一组关于招投标的数据,关键信息如下:
M
Mars Liu 已提交
4

fix bug  
张志晨 已提交
5
```sql
M
Mars Liu 已提交
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
-- 招标项目
create table invitation
(
    id         int primary key auto_increment,
    name       varchar(256),
    attachment text
    -- ignore more detail ...
);

-- 竞标企业
create table company
(
    id   int primary key auto_increment,
    name varchar(256)
    -- ignore more detail ...
);

-- 投标记录
create table bids
(
    id            int primary key auto_increment,
    invitation_id int references invitation (id),
    company_id    int references company (id)
    -- ignore more detail ...
);

```

Joe 想要找出参与了所有投标的企业(有围标嫌疑),那么这个查询应该怎么写?

M
Mars Liu 已提交
36 37
<hr/>

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

F
feilong 已提交
40 41
* `show databases;` 列出所有数据库
* `show tables;` 列出所有表
M
Mars Liu 已提交
42

M
Mars Liu 已提交
43 44
## 答案

fix bug  
张志晨 已提交
45
```sql
M
Mars Liu 已提交
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
select *
from company
where not exists(
        select *
        from invitation
        where not exists(
                select *
                from bids
                where invitation.id = bids.invitation_id
                  and bids.company_id = company.id
            )
    )
```

## 选项

### A

fix bug  
张志晨 已提交
64
```sql
M
Mars Liu 已提交
65 66 67 68 69 70 71 72
select *
from company
where id = all (select company_id
                from bids)
```

### B

fix bug  
张志晨 已提交
73
```sql
M
Mars Liu 已提交
74 75 76 77 78 79 80 81
select *
from company
where id = any (select company_id
                from bids)
```

### C

fix bug  
张志晨 已提交
82
```sql
M
Mars Liu 已提交
83 84 85 86 87 88 89
select *
from company
where company.id in (select distinct company_id from bids) 
```

### D

fix bug  
张志晨 已提交
90
```sql
M
Mars Liu 已提交
91 92 93 94 95 96 97 98
select *
from company
where exists(
              select *
              from bids
              where bids.company_id = company.id
          ) 
```