0

如果新行是该特定用户的第 4 行,是否可以在没有 else/if 的情况下创建一个脚本?

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

日期(日期时间),fk_player_id(整数),积分(整数)

这是我的插入:

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

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

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

希望提前帮助和感谢:-)

4

1 回答 1

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 上对其进行了测试,它运行良好。

于 2013-02-23T16:47:57.017 回答