从第二张表中按金额摘要提取redords

时间:2019-06-17 07:53:45

标签: mysql

我的查询:

SELECT fd.*
FROM `fin_document` as fd
LEFT JOIN `fin_income` as fi ON fd.id=fi.document_id
WHERE fd.dt_payment < NOW()
HAVING SUM(fi.amount) < fd.total_amount

wich显然是不正确的,必须从fin_document早于dt_payment的{​​{1}}检索所有记录。这部分没问题。但是我必须通过对此文件进行的付款来过滤它们。一份文件可以支付1笔以上(2,3,4,5 ...)。这些付款在NOW()中。 fin_income表中有列document_id,其中外键fin_income。问题(至少对我来说)是我没有特定的fin_income.document_id=fin_document.id标准,并且金额是由id表中的所有记录得出的。我还必须找到仍然没有付款的记录(它们在fin_income中没有行)。

fin_income

2 个答案:

答案 0 :(得分:1)

您可能只需要一个相关的子查询来测试收入

drop table if exists fin_document,fin_income;
create table fin_document
(id                 int(11),                 
dt_payment         date    ,                          
total_amount       decimal(10,2)
)   ;        


create table fin_income
( id                int(11)       ,
 document_id       int(11)       ,
 amount            decimal(10,2) 
);

insert into fin_document values
(1,'2019-05-31',1000),
(2,'2019-06-10',1000),
(3,'2019-07-10',1000);

insert into fin_income values
(1,1,5),(1,1,5);

SELECT fd.*,(select coalesce(sum(fi.amount),0) from fin_income fi where fd.id=fi.document_id) income
FROM `fin_document` as fd
WHERE fd.dt_payment < NOW() and
fd.total_amount > (select coalesce(sum(fi.amount),0) from fin_income fi where fd.id=fi.document_id);

+------+------------+--------------+--------+
| id   | dt_payment | total_amount | income |
+------+------------+--------------+--------+
|    1 | 2019-05-31 |      1000.00 |  10.00 |
|    2 | 2019-06-10 |      1000.00 |   0.00 |
+------+------------+--------------+--------+
2 rows in set (0.00 sec)

答案 1 :(得分:1)

我不确定我是否理解正确,但是您可以尝试以下方法:

SELECT fd.*, SUM(IFNULL(fi.amount, 0)) as sum_amount, COUNT(fi.amount) as count_amount
FROM `fin_document` as fd
LEFT JOIN `fin_income` as fi ON fd.id=fi.document_id
WHERE fd.dt_payment < NOW()

GROUP BY fd.id

HAVING sum_amount < fd.total_amount # condition for searching by sum of payments

AND count_amount = {needed_count}   # condition for searching by count of payments;
                                    # documents without payments will have
                                    # sum and count equal to 0

所有聚合都在SELECT部分进行,然后将所有文档按ID分组,以避免结果重复,并可以使用聚合结果(SUM,COUNT)。最后,您可以应用所需的条件(关于日期,已付款项或付款次数)。

注意:请注意GROUP BY会显着增加大量数据的执行时间。