使用带sum的内部连接时出现问题

bqucvtff  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(298)

我有两(2)张表:ps\ wk\ mp\卖方\交易\历史记录

以及ps\ wk\ mp\卖家\订单\状态

仅当当前状态=5时,我要合计卖家金额
为此,我写了这样一篇文章:

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\u customer\u seller=2,我得到这个4984.020000(4950+34.02),它是精确的
但是对于id\u customer\u seller=5,我得到了25.848000而不是null
有人能帮我吗?
也许你可以自己测试一下,这个代码:https://github.com/kulturman/fakerepo

dldeef67

dldeef671#

首先你的记录有逻辑问题, id_transaction 有两个相同的事务处理 id_transaction 但数量不同 state ! so id为的事务 41 有状态的 5 这就是为什么顾客 5 将不为空,因为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

这里的工作示例

相关问题