在select中优化oracle多个子查询

时间:2018-04-20 19:05:09

标签: sql oracle

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

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将结果作为单行使用。如果我想要包含更多“图像类型”,我需要包含更多的子查询。

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

3 个答案:

答案 0 :(得分:1)

您的查询应该没问题。它甚至可能是最有效的方法,索引在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;

答案 1 :(得分:1)

也许这个:

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可以接受多行,那么select会更简单。但如果是这样的话。我不确定它是否比你的选择效率更高,我猜(不试试)也是如此。 (你的前两个子查询需要在它们的结束括号后面加一个逗号btw)

以下内容也可以使用,具体取决于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

答案 2 :(得分:0)

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