一对多内部连接

时间:2019-04-17 11:38:46

标签: mysql sql database

所以,我的问题是。我有餐桌付款和餐桌收费,因此,一笔付款有很多收费,但一笔收费有一笔付款。我需要选择所有付款,其中一笔付款的所有费用总额!=一笔付款的所有费用。

代码示例

4:2
9:8

2 个答案:

答案 0 :(得分:0)

您也许可以不用加入就可以做到这一点,只需选择一个子项即可获得payment_charge的总和,并将其与每次付款的charge_summ进行比较:

select payment_account, payment_agreement, payment_pay, payment_charge
from payment 
where payment.charge_summ <> (select sum(payment_charge)
                        from charge 
                        where payment.payment_id = charge_payment_id)

编辑 您可以使用JOIN进行操作,而无需内部选择:

select payment_id,payment_account, payment_agreement, payment_pay, charge_summ,sum(payment_charge) 
from payment join
     charge
     on payment_id = charge_payment_id
group by payment_id,payment_account, payment_agreement, payment_pay,charge_summ
having charge_summ <> sum(payment_charge)

答案 1 :(得分:0)

在任何情况下,表结构都会有用,请尝试以下查询:

select payment_account, payment_agreement, payment_pay, payment_charge
from payment join
(select charge_payment_id, sum(payment_charge) as totally from charge group by 
charge_payment_id) A 
on payment_id = charge_payment_id and payment_charge != totally;

在这里,您首先要汇总费用并与结果进行比较。