繁体   English   中英

在选择中优化oracle多个子查询

[英]optimize oracle multiple subqueries in select

现在,我面临着一个我认为可以优化的查询。

select i.itemID,
(select image from imagetable where imageType = 1 and itemID = i.itemID)
(select image from imagetable where imageType = 2 and itemID = i.itemID)
(select image from imagetable where imageType = 5 and itemID = i.itemID)
from 
    item i
where
    i.itemID = 3

这是需要优化的示例,结果是java将其作为单行使用。 如果我想包含更多的“图像类型”,就需要包含更多的子查询。

所以问题是,我该如何优化呢?

您的查询应该没问题。 imagetable(itemitem, imageType)上使用索引甚至可能是最有效的方法。

规范的选择是条件聚合:

select i.itemID,
       max(case when it.imageType = 1 then it.image end),
       max(case when it.imageType = 2 then it.image end),
       max(case when it.imageType = 5 then it.image end)
from item i left join
     imagetable it
     on it.itemId = i.itemId and it.imageType in (1, 2, 5)
where i.itemID = 3
group by i.itemId;

也许这样:

select i.itemID, t1.image im1, t2.image im2, t5.image im5
from item i
left join imagetable t1 on t1.itemId = i.itemId and t1.imageType=1
left join imagetable t2 on t2.itemId = i.itemId and t1.imageType=2
left join imagetable t5 on t5.itemId = i.itemId and t1.imageType=5
where i.itemID = 3

“事实是结果被java作为单行使用”

这似乎非常严格,如果您的Java接受多个行,则选择会简单得多。 但是,如果那样的话。 但是,我不确定它是否比您选择的效率更高,我会猜测(不尝试)大致相同。 (您的前两个子查询在其结尾括号后面需要一个逗号)

根据image数据类型,以下内容也应起作用:

select i.itemID, 
  max(decode(imageType,1,image)) im1,
  max(decode(imageType,2,image)) im2,
  max(decode(imageType,5,image)) im5
from item i left join imagetable t on t.itemId = i.itemId 
where i.itemID = 3
group by i.itemID
select i.itemID, 
case when imageType = 1 then image else null end, 
case when imageType = 2 then image else null end, 
case when imageType = 5 then image else null end
from 
    item i left join
 imagetable t
 on t.itemId = i.itemId 
where
    i.itemID = 3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM