【问题标题】:Sql query to get data diffrence of total in 2 tablesSql查询获取2个表中总计的数据差异
【发布时间】:2016-07-26 22:49:06
【问题描述】:

我有两张桌子:

  1. booking - 记录订单详情

    id | booking_amount
    -------------------
    1  |            150
    2  |            500
    3  |            400
    
  2. payment - 记录订单付款

    id | booking_id | amount
    ------------------------
    1  |          1 |    100
    2  |          1 |     50
    2  |          2 |    100
    

我想查找所有未完成付款的预订。根据上述数据,我们预计答案是2,3,因为booking_id=1 的支付总和与booking_table 中对应的booking_amount 匹配。

【问题讨论】:

  • 我不明白你到底想要什么。你的答案是 2,3?
  • 请再次检查我的问题我已添加截图

标签: mysql sql join inner-join


【解决方案1】:

您需要使用外连接来组合您的两个表并查找您的条件。此外,您将需要使用 SUM(..) 函数来获取支付表中每个 id 的金额总和。

请试试这个:

select b.id from booking b 
left outer join -- cant be inner join because we lose id:3 in that case.
(
  select booking_id, SUM(amount) as Total 
  from payment group by booking_id
) p on b.id = p.booking_id
where b.booking_amount > Coalesce(Total,0) --Coalesce is required for such values coming NULL, like id:3, they will be assigned as 0.

【讨论】:

  • 当我尝试这个时它显示错误 Invalid use of group function
  • 我变了。但是刚刚通知它基本上打开了Jean的答案。我稍后会寻找另一种方法并再次更新我的答案。
  • 是的,我认为没有更好的解决方案。
  • 虽然此代码可能会回答问题,但提供有关 why 和/或 如何 它回答问题的额外上下文将显着改善其长期价值。请edit你的答案添加一些解释。
【解决方案2】:

要回答您的问题,您需要考虑两件事:

  1. 您希望每个预订行在您的表格payment 中的总金额

  2. 您想将booking_amount 表与payment 一起加入。


第 1 部分非常简单:

SELECT sum(amount) as TotalP, booking_id FROM payment GROUP BY booking_id

只是一个带有简单聚合函数的基本查询...


对于第 2 部分,我们想加入 booking_amountpayment;基本的JOIN 是:

SELECT * FROM booking b 
LEFT JOIN payment p ON b.id = p.booking_id

我们使用LEFT JOIN,因为我们可能有一些不在payment 表中的预订。对于这些预订,您将获得NULL 价值。我们将使用COALESCENULL 值替换为0


最后的查询是这样的:

SELECT b.id, COALESCE(TotalP, 0),  b.booking_amount
FROM
 booking b
LEFT JOIN
 (SELECT sum(amount) as TotalP, booking_id FROM payment GROUP BY booking_id) as T
ON  b.id = T.booking_id
WHERE COALESCE(TotalP, 0) < b.booking_amount

【讨论】:

  • 非常好它会帮助我写sql查询。
猜你喜欢
  • 2022-01-08
  • 2019-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-17
  • 2012-12-12
  • 1970-01-01
  • 2016-07-20
相关资源
最近更新 更多