假设我们有这四个表:
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
语句或以其他方式?
答案 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