将几个查询“ SELECT INTO ..”合并为一个

时间:2019-07-16 06:23:07

标签: sql oracle merge

我有以下选择列表:

  SELECT id
  INTO   val_abc
  FROM   table_x
  WHERE  symbol = 'abc';

  SELECT id
  INTO   val_xyz
  FROM   table_x
  WHERE  symbol = 'xyz';

  SELECT id...

是否可以将 SAME TABLE(!)中的几个SELECT合并为一个?

3 个答案:

答案 0 :(得分:2)

是的,您可以像下面这样组合这些查询:

select max(case symbol when 'abc' then id end),
       max(case symbol when 'def' then id end),
       max(case symbol when 'xyz' then id end)
  into val_abc, val_def, val_xyz
  from table_x
  where symbol in ('abc', 'def', 'xyz');

甚至使用数据透视表(Oracle 11或更高版本):

select v1, v2, v3
  into val_abc, val_def, val_xyz
  from (select id, symbol from table_x)
  pivot (max(id) for symbol in ('abc' v1, 'def' v2, 'xyz' v3));

dbfiddle demo

注意:如果您的查询遇到多个匹配的行应用程序,则在无值时抛出错误too many rowsno data found。我的解决方案使用聚合,因此不会出现错误-如果没有发现错误,则取最大值或null。 table_x的每个符号只有一个匹配的ID都没关系,但是请注意这一点。

答案 1 :(得分:1)

是的,例如几种方法

select id
from tablex
where symbol in ('abc', 'xyz')

select id 
from tablex
where symbol = 'abc'
   or symbol = 'xyz'

select id 
from tablex
where symbol = 'abc'
union all
select id
from tablex
where symbol = 'xyz'

答案 2 :(得分:0)

如果您确实愿意,可以使用join来表达这一点:

SELECT abc.id, xyz.id
INTO val_abc, val_xyz
FROM table_x abc JOIN
     table_x xyz
     ON abc.symbol = 'abc' AND
        xyz.symbol = 'xyz';