2016-09-01 5 views
0

私のSQLには、同じ条件に従って2つの結果フィールドがあります。今私はそれを2回書く必要があります。データベースコンパイラが自動的にコードを自動的に最適化しているのか、SQLを最適化するために他の方法を変更しなければならないのだろうか?条件が満たされている場合にOracleのコードを最適化する方法は?

select id,parent_id as p_Id,name, 
(case when exists(select * from t_group t2 where t1.id=t2.parent_id) 
then 2 else 1 end) type, 
(case when exists(select * from t_group t2 where t1.id=t2.parent_id) 
then 'true' else 'false' end) as is_Parent 
from t_group t1 

私はこのように変更しようとしましたが、失敗しました。

select id,parent_id as p_Id,name, 
(case when exists(select * from t_group t2 where t1.id=t2.parent_id) 
then 2 else 1 end) type, 
(case when type==1 
then 'true' else 'false' end) as is_Parent 
from t_group t1 

答えて

1

共通テーブル式またはインラインビューを使用して式を1度取得し、そのCTEまたはインラインビューの外で使用します。ここではインライン・ビューを使用して、私が何を意味するかである:左が参加していることを確認し、派生テーブルを作成する1以上を返すことはできませんしながら、

SELECT v.id, v.parent_id, v.name, v.type, case when v.type = 1 THEN 'TRUE' ELSE 'FALSE' END is_parent 
FROM 
(
select id,parent_id as p_Id,name, 
(case when exists(select * from t_group t2 where t1.id=t2.parent_id) 
then 2 else 1 end) type 
from t_group t1 
) v 
+0

「インラインビュー」の名前を指定する必要がありますか?多くのシステムで標準SQLが必要ですが、Oracleはそうではありません。 –

+0

いいえ、そうではありません。しかし、あなたはその列を参照したいと思うし、あいまいさがあります。私は私の答えを更新します。 –

0

私は左を使用して、それを書き換えるだろうが、行ごとに実行されている複数のクエリを避けるために参加行:

select t.id, 
     t.parent_id as p_id, 
     t.name, 
     case when c.parent_id is not null then 2 else 1 end as type, 
     case when c.parent_id is not null then 'true' else 'false' end as is_parent 
    from t_group t 
    left join (select parent_id, 
        row_number() over (partition by parent_id order by null) as rn 
       from t_group) c 
    on c.parent_id = t.id 
    and c.rn = 1 
+0

私はそれが最も効率的な方法だとは思わない。準結合がネストされたループであることを心配している場合は、共通のテーブル式で 'DISTINCT parent_id FR_ t_group'を選択し、それに左結合します。平均的にバッファが少なくなると思う。このようなことから、Oracleはセミ・ジョインのための明示的な結合構文を必要としています。 –

0
select id,parent_id as p_Id,name, 
     decode(t2.parent_id,NULL,1,2) type, 
     decode(t2.parent_id,NULL,'false','true') is_Parent 
    from t_group t1 
    left join(select distinct parent_id from t_group) t2 
    on t1.id=t2.parent_id 

の場合は、列PARENT_IDのインデックス(選択のサブクエリのように)オプティマイザの問題「索引レンジ・スキャン」または「高速全索引スキャン」(それが高速であることを理解する場合)が存在します。

関連する問題