| | |
| | | select |
| | | app.id, |
| | | app.payment_amount, |
| | | pl.id as purchase_ledger_id |
| | | -- 优先按入库单关联采购合同;入库单未审核/不存在时,回退按付款申请中的采购合同号关联, |
| | | -- 避免“新增付款”成功后明细中看不到该笔付款 |
| | | COALESCE( |
| | | (select min(pl_sir.id) |
| | | from stock_in_record sir |
| | | left join quality_inspect qi on sir.record_type = 10 and sir.record_id = qi.id |
| | | left join purchase_ledger pl_sir |
| | | on pl_sir.id = if(sir.record_type = 7, sir.record_id, qi.purchase_ledger_id) |
| | | where find_in_set(sir.id, apa.stock_in_record_ids) > 0 |
| | | and sir.approval_status = 1 |
| | | and sir.record_type in ('7','10')), |
| | | (select pl_no.id |
| | | from purchase_ledger pl_no |
| | | where pl_no.purchase_contract_number = apa.payment_content |
| | | order by pl_no.id |
| | | limit 1) |
| | | ) as purchase_ledger_id |
| | | from account_purchase_payment app |
| | | left join account_payment_application apa on app.account_payment_application_id = apa.id |
| | | left join stock_in_record sir on FIND_IN_SET(sir.id, apa.stock_in_record_ids) > 0 |
| | | -- 10 类型才关联质检表 |
| | | LEFT JOIN quality_inspect qi ON sir.record_type = 10 AND sir.record_id = qi.id |
| | | -- 动态关联采购(自动适配 7 和 10) |
| | | LEFT JOIN purchase_ledger pl |
| | | ON pl.id = IF(sir.record_type = 7, sir.record_id, qi.purchase_ledger_id) |
| | | WHERE sir.approval_status = 1 |
| | | AND sir.record_type IN ('7','10') |
| | | group by app.id, pl.id |
| | | ) t |
| | | left join purchase_ledger pl on t.purchase_ledger_id = pl.id |
| | | group by pl.id |