如何在单个查询中比较两个表的总和?

时间:2014-03-07 21:24:21

标签: mysql

http://sqlfiddle.com/#!2/fae8a/6

我有三张桌子 - 订单,order_line_items,order_payments。

我可以使用select语句汇总订单的总数和付款,但我似乎无法找出正确的语法,只返回“付款”加起来小于“总计”的订单(订单)没有全额付清)。

我错过了什么?

2 个答案:

答案 0 :(得分:2)

您需要使用HAVING子句按聚合函数过滤结果,还需要使用COALESCE()过滤掉空值

select 
    `orders`.`id`, 
    `order_payments`.`order_id`, 
    `order_payments`.`amount`, 
    `order_line_items`.`order_id`, 
    `order_line_items`.`price_each`, 
    `order_line_items`.`quantity`,
    COALESCE(SUM(`order_line_items`.`price_each` * `order_line_items`.`quantity`),0) as `order_total`,
    COALESCE(SUM(`order_payments`.`amount`),0) as `payments`
from 
    `orders` 
left join 
    `order_payments` on `order_payments`.`order_id` = `orders`.`id` 
left join 
    `order_line_items` on `order_line_items`.`order_id` = `orders`.`id`
group by 
    `orders`.`id`
HAVING   `payments` < `order_total`

Updated fiddle

来自评论的编辑

另一种重写查询的方法是使用子查询,您之前的查询为您提供了笛卡尔积

select 
    `o`.`id`,
(SELECT COALESCE(SUM(`price_each` * `quantity`),0) FROM `order_line_items` WHERE order_id =`o`.`id` ) as `order_total`,
(SELECT COALESCE(SUM(`amount`),0) FROM `order_payments` WHERE order_id =`o`.`id`) as `payments`
from 
    `orders` o
HAVING   `payments` < `order_total`

Without Having Clause

With Having Clause

答案 1 :(得分:1)

你不能使用sum()使用的地方。