有没有一种方法可以避免在SQL中使用UNION ALL?

时间:2020-07-09 14:17:24

标签: sql

我有多个查询,它们显示相同的变量。但是,唯一的区别是在WHERE条件下。即

SELECT (price*quantity) as total, date, CASE when type='Yes' then 'USA. YES' else 'USA. NO' end as name
from DB1
where name = 'manuf'
and export = 'yes'
union all

SELECT (price*quantity) as total, date, CASE when type='Yes' then 'BRAZIL. YES' else 'BRAZIL. NO' end as name
from DB1
where name = 'extra'
and export = 'yes'
and import = 'yes'

因此,我想节省一些时间,因为实际上这些查询要花很多时间才能运行,而使用UNION ALL会多次运行每个查询。我在考虑如何简化它,因此查询运行的时间更少。有没有机会避免使用UNION ALL?

1 个答案:

答案 0 :(得分:1)

您可以调整case表达式并展开where

select (price*quantity) as total, date,
       (case when name = 'manuf' and type = 'Yes' then 'USA. YES'
             when name = 'manuf' then 'USA. NO'
             when name = 'extra' and type = 'Yes' then 'BRAZIL. YES' 
             then 'BRAZIL. NO'
        end) as name
from DB1
where (name = 'manuf' and export = 'yes') or
      (name = 'extra' and export = 'yes' and import = 'yes');