如何避免关联CASE中的子查询呢?

时间:2017-07-10 09:34:05

标签: sql case correlated-subquery

假设我们有这四个表:

create table table_x(x number, title varchar2(100));

create table table_y(y number, x number, title varchar2(100));

create table table_z(z number, y number, x number, title varchar2(100));

create table table_main(z number, y number, x number);

根据规则,title中的每一行都需要获取table_main

select 
    case
         when z is not null
         then (select title from table_z where x = tm.x and y = tm.y and z = tm.z)

         when y is not null
         then (select title from table_y where x = tm.x and y = tm.y)

         when x is not null
         then (select title from table_x where x = tm.x)
     end as title
 from table_main tm;

我正在寻找一种更易读的解决方案,可以产生相同的结果。

有没有办法重构查询,用表连接替换case when语句或以其他方式?

1 个答案:

答案 0 :(得分:2)

我的方法是:

SELECT COALESCE(tz.title, ty.title, tx.title) AS mytitle
  FROM table_main tm
  LEFT OUTER JOIN table_x tx
    ON tx.x_number = tm.x_number
  LEFT OUTER JOIN table_y ty
    ON ty.x_number = tm.x_number
   AND ty.y_number = tm.y_number
  LEFT OUTER JOIN table_z tz
    ON tz.x_number = tm.x_number
   AND tz.y_number = tm.y_number   
   AND tz.z_number = tm.z_number