您可能想要创建两个历史表,第一个快速确定自上次运行过程以来发生的变化,第二个跟踪库存更改的历史。
第一个表是您上次运行此夜间(每天、每小时等)流程时存在的库存表的副本。(我会添加一个日期时间字段来跟踪该进程上次运行的时间)。此表与您的真实库存表一起使用序列号和相关字段(位置、状态等)确定已插入、删除或更新的内容。
第二个表是库存更改日志(意味着 SERIAL XXX 有多个条目)。每当库存发生变化时,通过将在前一个表中找到的记录复制到此表来填充此表。添加另一个字段:带有值的操作(插入、更新、删除)。
伪代码:
填充插入和更新
INSERT INTO inventory_transaction (serial_number,lastupdated,ACTION, location, status)
SELECT inventory.serial_number, NOW()
, IF(inventory_history.serial_number IS NULL, 'INSERT', 'UPDATE')
, inventory.location
, inventory.status
FROM inventory
LEFT JOIN inventory_history
ON inventory.serial_number = inventory_history.serial_number
WHERE NOT (inventory.location <=> inventory_history.location
AND inventory.status <=> inventory_history.status);
删除:
INSERT INTO inventory_transaction (serial_number, lastupdated, ACTION)
SELECT inventory_history.serial_number, NOW(), 'DELETE'
FROM inventory_history
LEFT JOIN inventory
ON inventory.serial_number = inventory_history.serial_number
WHERE inventory.serial_number IS NULL;
填充库存inventory_history 表:
TRUNCATE TABLE inventory_history;
INSERT INTO inventory_history(serial_number,lastchecked, location, status)
SELECT serial_number, NOW(), location, status
FROM inventory;
要查看特定时间点的库存情况:
SELECT inventory_transaction.*
FROM (SELECT serial_number, MAX(lastupdated) as last_date
FROM inventory_transaction
WHERE lastupdated <= 'point in time'
GROUP BY serial_number) AS correct_time
JOIN inventory_transaction
ON inventory_transaction.serial_number = correct_time.serial_number
AND inventory_transaction.lastupdated = correct_time.lastupdated
AND inventory_transaction.ACTION <> 'DELETED'