2014-01-15 32 views
1

我有這個查詢哪個不工作,即使我不知道它是否可能,我只想確認或任何其他方式如果有使用此查詢。在選擇查詢中獲得選定字段的替代方法

錯誤查詢:

select i.shipping, ii.sub_total, 
    round(ii.sub_total * (ii.item_tax/100)) taxed_amount, 
    round(ii.sub_total + taxed_amount) total, 
    round(total + i.shipping) paid_amount 
from ci_invoices i 
join ( 
    select invoice_id, sum(item_qty_total) sub_total, item_tax 
    from ci_invoice_items group by invoice_id 
    ) ii on i.invoice_id = ii.invoice_id 
where i.invoice_id = '15' limit 1 

右查詢:

SELECT i.shipping, ii.sub_total, 
     round(ii.sub_total * (ii.item_tax /100)) taxed_amount, 
     round(ii.sub_total + round(ii.sub_total * (ii.item_tax /100))) total, 
     round(round(ii.sub_total + round(ii.sub_total * (ii.item_tax /100))) + i.shipping) paid_amount 
FROM ci_invoices i 
JOIN (
    SELECT invoice_id, sum(item_qty_total) sub_total, item_tax 
    FROM ci_invoice_items 
    GROUP BY invoice_id 
    )ii ON i.invoice_id = ii.invoice_id 
WHERE i.invoice_id = '15' 
LIMIT 1 

正如你看到的選擇查詢時我不能使用taxed_amounttotal的差異。有沒有其他的方法來編寫我的正確查詢?

+1

你不能以這種方式在'同一級別'引用一個別名,所以無論是將它包裝在一個子查詢中,還是(更好)只是簡單地寫出來 - 就像你做的那樣 – Strawberry

回答

0

這個怎麼樣 -

select 
    i.shipping, 
    sum(ii.item_qty_total) sub_total, 
    round(sum(ii.item_qty_total * ii.item_tax/100)) taxed_amount, 
    round(sum(ii.item_qty_total * (1 + ii.item_tax/100))) total, 
    round(sum(ii.item_qty_total * (1 + ii.item_tax/100)) + i.shipping) paid_amount 
from ci_invoice_items ii, ci_invoices i 
where i.invoice_id = ii.invoice_id 
and i.invoice_id = '15' 
group by ii.invoice_id 

在上面的查詢的查詢計劃看起來比當前正確的查詢計劃簡單。這裏是一個SQL Fiddle