Oracle:如何使用多个选择子查询优化SQL

时间:2020-02-04 07:13:17

标签: sql oracle subquery query-optimization query-performance

TABLENAME:表格

列:

Id | name | c1 | c2 | c3 | c4 | b1 | b2 | b3 | b4 | time

查询:

Select (case when select count(*) from s1 where s1.b1 = 1
                     then select top 1 from s1 where s1.b1 = 1 order by time desc
                     else s2.id 
             end) as COLUMNONE,
       (case when select count(*) from s1 where s1.b2 = 1
                       then select top 1 from s1 where s1.b2 = 1 order by time desc
                       else s2.name 
               end) as COLUMNTWO,
       (case when select count(*) from s1 where s1.b3 = 1
                       then select top 1 from s1 where s1.b3 = 1 order by time desc
                       else s2.c1 
             end) as COLUMNTHREE,
       (case when select count(*) from s1 where s1.b4 = 1
                     then select top 1 from s1 where s1.b4 = 1 order by time desc
                     else s2.c2 
             end) as COLUMNFOUR
 from 
     table s1, table s2
 where s1.id = s2.id;


s1 table records
uniqueId | Id | name | c1 | c2 | c3 | c4 | b1 | b2 | b3 | b4 | time
  a        12   abc    qw   tr   cd   hi    1    1    1    1    1
  b        13   abc    qw   tr   cd   hi    1    1    1    1    2
  c        14   abc    qw   tr   cd   hi    1    1    1    1    3
  d        12   null   null null cd   hi    1    0    0    0    4
  e        13   abcef  qw   tr   cd   hi    1    1    0    0    5
  f        14   null   null null cd   hi    1    0    0    0    6
  g        12   abcji  qwer trft cd   hi    1    1    1    0    7
  h        13   null   null null cd   hi    1    0    0    0    8
  i        14   abc    qw   tryr cdoi hi    1    0    1    1    9
  j        12   abc    qw   trqw cdpl hi    1    0    0    1    10
  k        13   abcij  qw   tr   cd   hi    1    1    0    0    11
  l        14   abc    qw   troi cd   hi    1    0    1    0    12

s2 table records will contain the latest records
 Id | name | c1 | c2 | c3 | c4 | b1 | b2 | b3 | b4 | time
 12   abc    qw   tr   cdpl hi    1    0    0    1    10
 13   abcij  qw   tr   cd   hi    1    1    0    0    11
 14   abc    qw   troi cd   hi    1    0    1    0    12



OUTPUT :
  Id(COLUMNONE) | name(COLUMNTWO)   | c1(COLUMNTHREE) | c2(COLUMNFOUR) | 
  12                abcji                   qw              trqw
  13                abcij                   qw              tr
  14                abc                     qw              tryr

如果我有多个选择子查询,有人可以帮助我如何优化吗?

0 个答案:

没有答案