更好的结构化oracle sql查询

时间:2017-05-07 12:03:45

标签: sql oracle11g

在Oracle 11数据库中,我有2个表(CAR和CAR_BRAND):

CAR有以下

car_id  |brand
1       |Audi
2       |BMW
3       |VW

CAR_BRAND有以下

brand
Audi
Bmw

直接使用INNER JOIN加入两个表

select c.* from car c
inner join car_brand cb on cb.brand = c.brand;

我要求当CAR_BRAND表为空时,然后选择CAR中的所有记录,否则从CAR加入CAR_BRAND表中选择*。

可以按照以下方式完成:

SELECT c.* FROM car c JOIN car_brand cb ON cb.brand = c.brand
UNION ALL
SELECT c.*
FROM car c
WHERE NOT EXISTS
(SELECT c.* FROM car c JOIN car_brand cb ON cb.brand = c.brand
);

这很好,但是,有没有更好,更有效的SQL来获得最终结果而不是使用UNION ALL?

1 个答案:

答案 0 :(得分:0)

您可以在检索汽车时使用变量计算 car_brand 记录,然后使用or测试这两个案例:

select     car_id, brand
from       (
                select     c.*, 
                           cb.brand as match_brand, 
                           @r := @r + if(cb.brand is null,0,1)
                from       car c
                cross join (select @r := 0) init
                left join  car_brand cb
                        on cb.brand = c.brand
           ) base
where      @r = 0 or match_brand is not null