在select查询中获取所选字段的替代方法

时间:2014-01-15 09:49:47

标签: mysql sql

我有这个查询无效,即使我不知道是否可能,我只是想确认或任何替代方式,如果有使用此查询。

错误的查询:

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 个答案:

答案 0 :(得分: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