mysql - 在选择查询中获取选定字段的替代方法

标签 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 的区别。有没有其他方法可以编写我的正确查询?

最佳答案

这个怎么样-

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/

相关文章:

sql - SQL 中的连接顺序重要吗?

c# - 如何跟踪表行之间的 ID/ParentID 关系?

sql - 查询以替换 SQL 中的逗号?

mysql - 将 MySQL 源结果输出到日志文件

mysql - 具有带有动态 SQL 的存储过程,可创建大量结果选项卡

php - GROUP BY 到数组

php - 跨数据库创建关系表(laravel)

php - 在php中显示最近上传的图像仅显示与提交到该die的其他数据相对应的单个图像

mysql - 如何确定metricbeat mysql的理想期限?

php - 显示结果不重复