【发布时间】:2021-06-17 17:22:30
【问题描述】:
有一张关于汽车的数据表。
| model_id | color |
|---|---|
| 1 | black |
| 1 | green |
| 2 | black |
| 3 | blue |
| 3 | white |
| 4 | red |
| 5 | white |
| 5 | black |
任务是如果模型可以是黑色的,那么就只留下它(黑色),如果模型不能是黑色的,那么就留下它所有的颜色:
| model_id | color |
|---|---|
| 1 | black |
| 2 | black |
| 3 | blue |
| 3 | white |
| 4 | red |
| 5 | black |
第一种方式:
create table black_cars as
(select * from cars where color = 'black')
with data;
create table not_black_cars as (
select c.* from cars as c
where not exists (select 1 from black_cars as bc where bc.model_id = c.model_id)
with data;
select * from black_cars
union
select * from not_black_cars;
第二种方式:
select * from cars where color = 'black
union
select * from cars as c
inner join
(select distinct model_id from cars except select model_id from cars where color = 'black') as nbc
on c.model_id = nbc.model_id
第三种方式(低性能):
select * from cars where color = 'black
union
select * from cars where model_id not in
(select model_id from cars where color = 'black)
我不确定这两种方法中的哪一种是最佳的。如果有人能提出最好的方法,我将不胜感激。
【问题讨论】:
标签: sql union teradata except not-exists