這是很容易的,如果你添加一個主鍵到表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上測試它,它運行良好。
您可以創建一個觸發器。但是,我可能會創建一個'VIEW'來獲取最後3個點。 – Kermit 2013-02-23 15:15:31
爲什麼一個觀點......是更輕的?不想要很多行?每天有超過10萬用戶獲得5-10次點數。 – Mansa 2013-02-23 15:25:58
你知道'VIEW'是什麼嗎? – Kermit 2013-02-23 15:28:42