从三个表返回null的sum(amount)

时间:2014-05-11 09:18:33

标签: mysql sql

我有以下表格

create table supplier_paid_details(
    id bigint(10) NOT NULL AUTO_INCREMENT,
    payment_mode varchar(20),
    payment_date date,
    add_date timestamp DEFAULT 0,
    status varchar(20),
    supp_payment_id bigint(10) NOT NULL,
    primary Key(id),
    CONSTRAINT fk_paid FOREIGN KEY (supp_payment_id)
    REFERENCES supplier_payment_details(id)
    );

create table supplier_paid_check(
id bigint(10) NOT NULL AUTO_INCREMENT,
check_no bigint(10) NOT NULL, 
dated date,
payable_at varchar(50),
paid_to_acc_no varchar(30),
paid_to_bank varchar(30),
paid_to_branch varchar(30),
spd_id bigint(10),
add_date timestamp DEFAULT 0,
amount float(10,2),
status varchar(20),
primary Key(id),
CONSTRAINT fk_ckeck FOREIGN KEY (spd_id)
REFERENCES supplier_payment_details(id)
);



create table supplier_paid_online(
id bigint(10) NOT NULL AUTO_INCREMENT,
pay_ref_no varchar(50),
paid_from_bank varchar(50),
from_acc_no varchar(50),
paid_to_acc_no varchar(30),
paid_to_bank varchar(30),
paid_to_branch varchar(30),
spd_id bigint(10),
add_date timestamp DEFAULT 0,
amount float(10,2),
status varchar(20),
primary Key(id),
CONSTRAINT fk_online FOREIGN KEY (spd_id)
REFERENCES supplier_paid_details(id)
);

create table supplier_paid_cash(
id bigint(10) NOT NULL AUTO_INCREMENT,
to_person varchar(40),
designation varchar(40),
receipt_no varchar(30),
spd_id bigint(10),
add_date timestamp DEFAULT 0,
amount float(10,2),
status varchar(20),
primary Key(id),
CONSTRAINT fk_cash FOREIGN KEY (spd_id)
REFERENCES supplier_paid_details(id)
);

在此,我想总结supplier_paid_checksupplier_paid_cashsupplier_paid_online的金额。

因为我正在使用以下查询,但这显示为null。

 select sum(ca.amount+ch.amount+onl.amount) as amount from
supplier_paid_details as pd
left join supplier_paid_cash as ca
on pd.id=ca.spd_id
left join supplier_paid_check as ch
on pd.id=ch.spd_id
left join supplier_paid_online as onl
on pd.id=onl.spd_id
where pd.supp_payment_id=1;

2 个答案:

答案 0 :(得分:1)

我认为在您的三个表格中,至少有一行amount的值为NULL。这最终会导致NULL,因为DBMS无法确定如何与其他值结合使用此值。但有一条出路:您可以告诉您的DBMS如何处理NULL值。使用IFNULL

select
    sum(IFNULL(ca.amount, 0) + IFNULL(ch.amount, 0) + IFNULL(onl.amount, 0)) as amount 
from
    supplier_paid_details as pd left join supplier_paid_cash as ca on pd.id=ca.spd_id
    left join supplier_paid_check as ch on pd.id=ch.spd_id
    left join supplier_paid_online as onl on pd.id=onl.spd_id
where
    pd.supp_payment_id=1;

点击IFNULL MySQL Docs了解详情。

答案 1 :(得分:0)

试试这个:

select sum(
              coalesce(ca.amount, 0)
            + coalesce(ch.amount, 0)
            + coalesce(onl.amount, 0)
          ) as amount from
....

或者这个:

select sum(ca.amount) + sum(ch.amount) + sum(onl.amount) as amount from
....