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

```mysql
-- 招标项目
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/>

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

M
Mars Liu 已提交
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 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
## 答案

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

```mysql
select *
from company
where id = all (select company_id
                from bids)
```

### B

```mysql
select *
from company
where id = any (select company_id
                from bids)
```

### C

```mysql
select *
from company
where company.id in (select distinct company_id from bids) 
```

### D

```mysql
select *
from company
where exists(
              select *
              from bids
              where bids.company_id = company.id
          ) 
```