如何在条件下优化代码? [英] How to optimized code for oralcle case when condition?

查看:102
本文介绍了如何在条件下优化代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的sql根据相同的条件有两个结果字段,现在我要写两次,我想知道数据库编译器是否已经自动优化代码还是我必须改变其他方式来优化sql? br />

 选择 id,parent_id  p_Id, name,
case 存在时选择 * 来自 t_group t2 其中 t1.id = t2.parent_id)
然后 2 其他 1 结束类型
案例 存在 select * 来自 t_group t2 其中 t1.id = t2.parent_id)
然后 ' true ' else ' false' end as is_Parent
来自 t_group t1



我试图改变它,但失败了。

  select  id,parent_id  as  p_Id,name,
case 存在 select * < span class =code-keyword> from t_group t2 where t1.id = t2.parent_id)
然后 2 else 1 结束类型
案例 类型== 1
然后 ' true' else ' false' end as is_Parent
来自 t_group t1





我尝试了什么:



我试图改变它,但失败了。

select id, parent_id为p_Id,name,

(存在时的情况(从t_group t2中选择*,其中t1.id = t2.parent_id)

然后2其他1结束)类型,

(类型== 1

t时的情况hen'true'其他'false'结束)as_text

来自t_group t1

解决方案

你必须自己加入一个包含分层数据的表!请参阅:分层查询 [ ^ ]





有关联接的详细信息,请参阅:请参阅: SQL连接的可视化表示 [ ^ ]

My sql have two result field according to the same condition,now I have to write it two time,I wonder whether the database compiler have already optimize the code automatically or I have to change the other way to optimize the sql?

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


I have try to change it,but failed.

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 



What I have tried:

I have try to change it,but failed.
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

解决方案

You have to self join a table with hierarchical data!!! See: Hierarchical Queries[^]


For further information about joins, see: See: Visual Representation of SQL Joins[^]


这篇关于如何在条件下优化代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆