左联接返回多行而不是一行

时间:2020-02-08 20:23:25

标签: mysql sql

我有三个表(tblOrder,tblOrder_Item,tblCredit),但是当我使用左联接时, tblCredit 显示3行而不是1行。

tblOrder

idOrder    date         idUser
1          2020-01-01   1
2          2020-02-02   2
3          2020-03-03   3

tblOrder_Item

idOrder_Item   qty   price   idProduct   idOrder
1              3     30      1           1
2              2     20      1           1
3              5     50      1           2

tblCredit

idCredit   amount   idOrder
1          15       1
2          10       2

实际结果是:

idOrder   priceTotal   credit   remainingPayment
1         130          **30**    100
2         250          10        240

但我的预期结果是:

idOrder   priceTotal   credit   remainingPayment
1         130           15        115
2         250           10        240

该如何解决?我需要将tblCredit.amount移至tblOrder吗?谢谢

对不起,我忘记了链接。这里是链接http://sqlfiddle.com/#!9/4ead83/1

2 个答案:

答案 0 :(得分:0)

每个订单不得超过一个信用点,您可以按以下方式使用汇总:

select
    o.iOrder,
    sum(oi.price * qty) priceTotal,
    coalesce(c.amount, 0) credit,
    sum(oi.price * qty) - coalesce(c.amount, 0) remainingPayment
from tblOrder o
inner join tblOrder_Item oi on oi.iOrder = o.iOrder
left join credit c on c.iOrder = o.iOrder
group by o.iOrder, c.amount

我在带left join表时使用了credit:大概有些订单可能还没有积分。

另一方面,如果一个订单可能有多个积分,那么您需要在子查询中汇总每个订单的价格和积分,然后将结果与订单表合并:

select
    o.idOrder,
    oi.priceTotal,
    coalesce(credit, 0) credit,
    oi.priceTotal - coalesce(credit, 0) remainingPayment
from 
    tblOrder o
    inner join (select iOrder, sum(price * qty) priceTotal from tbllOrder_Item group by iOrder) oi
        on oi.iOrder = c.iOrder
    left join (select iOrder, sum(amount) credit from tblCredit group by iOrder) c 
        on c.iOrder = o.iOrder

答案 1 :(得分:0)

您可能会发现let dataObject = {}; function appendDiv() { e = this.event.target; //this id changes each time when the function is called var current_id = e.id; // here I had to initialized it because if I didn't, it would appear an error "TypeError: dataObject[(intermediate value)] is undefined" dataObject[`${current_id}`] = {}; $('#creates').submit(function (event) { var i, j; for (i = 0; i < nbr_group.value; i++) { inputlist = []; for (j = 0; j < 3; j++) { formChild = document.querySelectorAll('.period-select')[j].value; inputlist[j] = formChild; } dataObject[`${current_id}`][`${i}`] = { firstvalue: inputlist[0], secondvalue: inputlist[1], thirdvalue: inputlist[2] } } }); } / // the first call: dataObject = { '1': { '1': { '1': 'some values' }, '2': { '1': 'another value' } } }; //the second call or third or... : dataObject = { '1': { '1': { '1': 'some values' }, '2': { '1': 'another value' } }, '2': {} }; 可以满足您的要求:

union all