Teradata SQL 助手 - NOT EXISTS、INNER JOIN、IN 或其他方式

问题描述

有一张关于汽车的数据表。

model_id 颜色
1 黑色
1 绿色
2 黑色
3 蓝色
3 白色
4 红色
5 白色
5 黑色

任务是,如果模型可以是黑色的,那么只留下它(黑色),如果模型不能是黑色的,那么留下它的所有颜色:

model_id 颜色
1 黑色
2 黑色
3 蓝色
3 白色
4 红色
5 黑色

第一种方式:

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)

我不确定这两种方式中的任何一种是最佳的。如果有人能提出最好的方法,我将不胜感激。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)