表中最多3行为每个用户

时间:2013-02-23 14:44:51

标签: php mysqli query-optimization

如果新行是该特定用户的第4行,是否可以在没有else的情况下创建脚本?如果删除用户的最旧行?

我有一个名为points_history的表。字段是:

日期(日期时间), fk_player_id(INT), 点(INT)

这是我的插页:

mysqli_query($mysqli,"INSERT INTO points_history (date,fk_player_id,points) VALUES (NOW(),$player,$points)");

这个原因我希望能够回到球员的历史和检查点,但只有最后3分并且不想要一张有数百万行的桌子。

可以在一个SQL查询中完成吗?

希望得到帮助并提前致谢: - )

1 个答案:

答案 0 :(得分:1)

如果您向表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上进行了测试,运行正常。