DoubleNotExists.md 1.5 KB
Newer Older
M
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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
# Double Not Exists Check

风控部们的数据库中有一组关于招投标的数据,关键信息如下:

```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 想要找出参与了所有投标的企业(有围标嫌疑),那么这个查询应该怎么写?

## 答案

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