在 MySQL 中,如何使用连接的 table 中的单行来过滤掉 GROUP_CONCAT 中不需要的日期?

In MySQL, how can I use a single row from a joined table to filter out unwanted dates in a GROUP_CONCAT?

我有一个 loan table 和一个 loan_status table。 loan table 包括 loan_iddate_issued 等列。在这里,我有一个获取 OTHER 贷款的 date_issued 的查询:

(select GROUP_CONCAT(Date(lj.date_issued) SEPARATOR ', ') from loan lj INNER JOIN client clj ON (clj.client_id = lj.client_id) 

where clj.client_id = '2299629' and lj.id != l.id) as other_loan_issue_dates,

因为这个客户有 7 笔贷款,所以我有一个这样的 table,有 6 个逗号分隔的日期:

问题:

我需要从 other_loan_issue_dates 中排除在 loan_status table 中具有 status_id27 的任何 loan 并且status_idloan_status table 中那个 loan 的最后一个条目。每笔贷款都有许多状态。

这是一个例子:

此查询显示 test 列,确定是否应在 other_loan_issue_dates:

中过滤掉它
select status_id = 27 as test from loan_status ls where loan_id = 2052456 ORDER BY datestamp DESC LIMIT 1;

以下错误未完运行:

(select GROUP_CONCAT(Date(lj.date_issued) SEPARATOR ', ') from loan lj INNER JOIN client clj ON (clj.client_id = lj.client_id) 

JOIN loan_status ls ON ls.status_id = (
select status_id from loan_status ls where loan_id = 2052456 ORDER BY datestamp DESC LIMIT 1
)

where clj.client_id = '2299629' and lj.id != l.id and ls.status_id != 27) as other_loan_issue_dates,

我也尝试了以下方法,但我不知道它是否有效,因为它似乎使结果相乘:

(select GROUP_CONCAT(Date(lj.date_issued) SEPARATOR ', ') from loan lj INNER JOIN client clj ON (clj.client_id = lj.client_id) 

LEFT OUTER JOIN loan_status ls ON (ls.loan_id = lj.id)

where clj.client_id = '2299629' and lj.id != l.id and (select status_id = 27 as test from loan_status ls where loan_id = ls.loan_id ORDER BY datestamp DESC LIMIT 1) = 0) as other_loan_issue_dates,

如何使用最后的 loan_status 行,检查它的 status_id 是否为 27,如果是,则排除 loan?

我不确定我是否正确回答了您的查询,因为这只是一些较大查询的一部分。但是,我建议您尝试这样的操作:

SELECT GROUP_CONCAT(Date(lj.date_issued) SEPARATOR ', ')
FROM loan lj
INNER JOIN client clj ON (clj.client_id = lj.client_id) 
WHERE clj.client_id = '2299629'
AND lj.id != l.id
AND lj.loan_id NOT IN (SELECT loan_id from loan_status WHERE status_id = 27)

SELECT loan_id from loan_status WHERE status_id = 27 会为您提供具有 status_id=27 的贷款 ID。然后你输入 NOT IN 告诉 MySQL 排除此类贷款。