如果您向表中添加主键,这很容易做到points_history
。
第 1 部分:
使用以下脚本将主键添加points_history_id
到表中:
ALTER TABLE points_history RENAME TO points_history_old;
CREATE TABLE points_history
(
`points_history_id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`date` datetime NOT NULL,
`fk_player_id` int(11) NOT NULL,
`points` int(11) NOT NULL,
PRIMARY KEY (`points_history_id`)
);
INSERT INTO points_history (date, fk_player_id, points)
SELECT date, fk_player_id, points
FROM points_history_old;
-- Drop table if migration succeeded (up to you)
-- DROP TABLE points_history_old;
这只需要运行一次!
第 2 部分:
现在您可以使用以下 SQL 脚本添加新记录并删除过时的记录:
-- First insert the new record
INSERT INTO points_history (date,fk_player_id,points)
VALUES (NOW(),:player,:points);
-- Create temporary table with records to keep
CREATE TEMPORARY TABLE to_keep AS
(
SELECT points_history_id
FROM points_history
WHERE fk_player_id = :player
ORDER BY date DESC
LIMIT 3
);
SET SQL_SAFE_UPDATES = 0;
-- Delete all records not in table to_keep
DELETE FROM points_history
WHERE points_history_id NOT IN (SELECT points_history_id FROM to_keep);
SET SQL_SAFE_UPDATES = 1;
-- Drop temporary table
DROP TEMPORARY TABLE to_keep;
如果您使用支持事务的数据库,我强烈建议将此脚本包装在事务中。我在 MySQL 5.5.29 上对其进行了测试,它运行良好。