我有这个查询不起作用,即使我不知道它是否可能,我只是想确认或任何其他方式是否可以使用此查询。
错误查询:
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_amount
和 total
的区别。有没有其他方法可以编写我的正确查询?
最佳答案
这个怎么样-
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
关于mysql - 在选择查询中获取选定字段的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21134024/