繁体   English   中英

将内部联接与sum一起使用时出现问题

[英]Issue while using inner join with sum

我有两(2)个表: ps_wk_mp_seller_transaction_history

在此处输入图片说明 ps_wk_mp_seller_order_status

在此处输入图片说明

仅在current_state = 5时,我才希望总计Seller_amount

为此,我写了这个:

select sum(seller_amount) as seller_amount
from ps_wk_mp_seller_transaction_history th inner join 
     ps_wk_mp_seller_order_status os
     on os.id_order = th.id_transaction and
        os.current_state = 5 and
        th.id_customer_seller = 2;

对于id_customer_seller = 2我得到了4984.020000(4950 + 34.02) ,这是准确的

但是对于id_customer_seller = 5我得到25.848000而不是NULL

有人能帮我吗?

也许您可以测试一下自己,这是代码: https : //github.com/kulturman/fakerepo

首先您的记录有一些逻辑问题, id_transaction有两个具有相同id_transaction但数量不同和state不同的交易! 因此ID为41交易的状态为5 ,为什么客户5不会为null,因为41处于状态5。

要解决这个问题

每个交易的交易ID必须是唯一ID,以便区分交易状态和金额

查询应该是这样的

select sum(seller_amount) as seller_amount
from ps_wk_mp_seller_transaction_history th 
left join ps_wk_mp_seller_order_status os 
  on os.id_order=th.id_transaction
where 
  th.id_customer_seller = 2
  and  os.current_state=5 

这里的工作示例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM