我有一个需要优化的子查询。它使用
加入itemInventory 3次左外连接
有没有办法用UNIONs做到这一点?... 3列从每个连接中获取数据,' LastDate'我发现很难设想一个查询来替换那个效率更高的查询。
以下是查询:
select
ii1.vendorno,
ii1.Quantity1,
ii3.date1,
ii1.fgspecialpo,
ii1.itemid,
ii1.LastDate as [LastDate1],
ii2.LastDate as [LastDate2],
ii3.LastDate as [LastDate3],
ii1.qtytype as [qtytyp], ii1.quantity2 as [qty2], ii2.Quantity1 as [itemsAddlQty],
ii3.quantity1 as [Exp Qty]
from iteminventory ii1
left outer join (select * from iteminventory where qtytype=11 ) ii2 on ii1.itemid=ii2.itemid and ii1.fgspecialpo=ii2.fgspecialpo and ii1.vendorno=ii2.vendorno
left outer join (select * from iteminventory where qtytype=1 ) ii3 on ii1.itemid=ii3.itemid and ii1.fgspecialpo=ii3.fgspecialpo and ii1.vendorno=ii3.vendorno
答案 0 :(得分:2)
UNION不会在这里帮助你。 UNION用于组合两个结果集,而不是您在此处拥有的结果集。您当然可以简化此操作以使用连接而不是那些子查询。我怀疑它在实际的执行计划中没有太大的区别。如果性能有问题,我们需要查看包含索引的表定义。这是你如何转换这个简单的使用连接。
SELECT ii1.vendorno
, ii1.Quantity1
, ii3.date1
, ii1.fgspecialpo
, ii1.itemid
, ii1.LastDate AS [LastDate1]
, ii2.LastDate AS [LastDate2]
, ii3.LastDate AS [LastDate3]
, ii1.qtytype AS [qtytyp]
, ii1.quantity2 AS [qty2]
, ii2.Quantity1 AS [itemsAddlQty]
, ii3.quantity1 AS [Exp Qty]
FROM iteminventory ii1
LEFT OUTER JOIN iteminventory ii2 ON ii1.itemid = ii2.itemid
AND ii1.fgspecialpo = ii2.fgspecialpo
AND ii1.vendorno = ii2.vendorno
AND ii3.qtytype = 11
LEFT OUTER JOIN iteminventory ii3 ON ii1.itemid = ii3.itemid
AND ii1.fgspecialpo = ii3.fgspecialpo
AND ii1.vendorno = ii3.vendorno
AND ii3.qtytype = 1
答案 1 :(得分:2)
如果我理解正确,我认为只需根据 qtytype 列的值显示不同列中的数据。我认为你不需要加入。
检查这是否适合您:
SELECT
vendorno,
Quantity1,
CASE WHEN qtytype=1 THEN date1 ELSE NULL END as date1,
fgspecialpo,
itemid,
LastDate as [LastDate1],
CASE WHEN qtytype=11 THEN LastDate ELSE NULL END as [LastDate2],
CASE WHEN qtytype=1 THEN LastDate ELSE NULL END as [LastDate3],
qtytype as [qtytyp],
quantity2 as [qty2],
CASE WHEN qtytype=11 THEN Quantity1 ELSE NULL END as [itemsAddlQty],
CASE WHEN qtytype=1 THEN quantity1 ELSE NULL END as [Exp Qty]
FROM iteminventory