1 -- Add issue_id to accountlines table
2 ALTER TABLE accountlines ADD issue_id INT(11) NULL DEFAULT NULL AFTER accountlines_id;
4 -- Close out any accruing fines with no current issue
5 UPDATE accountlines LEFT JOIN issues USING ( itemnumber, borrowernumber ) SET accounttype = 'F' WHERE accounttype = 'FU' and issues.issue_id IS NULL;
7 -- Close out any extra not really accruing fines, keep only the latest accring fine
9 LEFT JOIN (SELECT MAX(accountlines_id) AS keeper,
13 WHERE accounttype = 'FU'
14 GROUP BY borrowernumber, itemnumber
15 ) a2 USING ( borrowernumber, itemnumber )
16 SET a1.accounttype = 'F'
17 WHERE a1.accounttype = 'FU'
18 AND a1.accountlines_id != a2.keeper;
20 -- Update the unclosed fines to add the current issue_id to them
21 UPDATE accountlines LEFT JOIN issues USING ( itemnumber ) SET accountlines.issue_id = issues.issue_id WHERE accounttype = 'FU';