聚合现有查询以适用于多行

时间:2019-03-27 17:51:41

标签: mysql

我有一个分类帐表,现在我有能力根据某人的付款历史查找日期或NULL(如果有人拖欠了)。我需要一个查询,使我能够查找所有拖欠的成员,而不只是一个特定的成员。

我需要能够运行查询以获取任何拖欠的成员并向我返回member_id和拖欠日期。

基本上,用于查找特定成员违约行为的原始查询仅执行每个成员而不是特定成员。

我尝试过:

SELECT DISTINCT member_id, created_at FROM member_ledger_items WHERE 
balance > 0 and id > (
    IFNULL(
        (SELECT id from member_ledger_items WHERE balance <= 0 and member_ledger_items.deleted_at is NULL GROUP BY member_id ORDER BY created_at, id desc LIMIT 1),
        0
    )
) and `member_ledger_items`.`deleted_at` is null GROUP BY member_id order by created_at asc, id asc;

这是查找特定成员是否欠款的查询:

select `created_at` from `member_ledger_items` where `member_id` = ? and `balance` > 0 and `id` > 
(
IFNULL(
(select `id` from `member_ledger_items` where `member_id` = ? and `balance` <= 0 and `member_ledger_items`.`deleted_at` is null order by `created_at` desc, `id` desc limit 1)
, 0)
) 
and `member_ledger_items`.`deleted_at` is null order by `created_at` asc, `id` asc limit 1;

这是member_ledger_items表的创建语法:

CREATE TABLE `member_ledger_items` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `member_id` int(10) unsigned NOT NULL,
  `status` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `type` enum('credit','debit') COLLATE utf8_unicode_ci NOT NULL,
  `category` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `memo` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `amount` decimal(13,3) DEFAULT NULL,
  `autopay` tinyint(1) DEFAULT NULL,
  `late` tinyint(1) DEFAULT NULL,
  `date` date NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `deleted_at` timestamp NULL DEFAULT NULL,
  `balance` decimal(13,3) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=53596 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

我需要带有member_id和开始拖欠日期的行。

这可能吗?

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

SELECT `member_id`, 
       (SELECT `created_at` 
        FROM   `member_ledger_items` AS MLI2 
        WHERE  `balance` > 0 
               AND MLI2.`member_id` = MLI.`member_id` 
               AND `id` > ( Ifnull((SELECT `id` 
                                    FROM   `member_ledger_items` AS MLI3 
                                    WHERE  `balance` <= 0 
                                           AND MLI3.`member_id` = 
                                               MLI2.`member_id` 
                                           AND MLI3.`deleted_at` IS NULL 
                                    ORDER  BY `created_at` DESC, 
                                              `id` DESC 
                                    LIMIT  1), 0) ) 
               AND MLI2.`deleted_at` IS NULL 
        ORDER  BY `created_at` ASC, 
                  `id` ASC 
        LIMIT  1) AS created_date 
FROM   `member_ledger_items` AS MLI 
GROUP  BY `member_id`; 

最终成为解决方案