有没有一种方法可以避免sql中的联合?

brc7rcf0  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(291)

我有多个查询,它们显示相同的变量。然而,唯一的区别是在哪里的条件。即

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可以多次运行每个查询。我在考虑如何使它不那么复杂,这样查询运行的时间就少了。有没有任何机会避免所有的工会?

zf2sa74q

zf2sa74q1#

您可以调整 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');

相关问题