【问题标题】:Max 3 rows in table for each user每个用户的表中最多 3 行
【发布时间】:2013-02-23 14:44:51
【问题描述】:

如果新行是该特定用户的第 4 行,是否可以在不使用 else/if 的情况下为该用户删除最旧的行?

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

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

这是我的插入:

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

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

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

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

【问题讨论】:

  • 您可以创建触发器。但是,我可能只会创建一个 VIEW 来获取最后 3 个点。
  • 为什么是视图... 是否更轻量级?不想要很多行?每天有超过 100.000 名用户获得 5-10 次积分。
  • 你知道VIEW是什么吗?
  • 显然不是。虽然不正确。它存储一个 sql 查询,因此当调用它时它将执行。

标签: php mysqli query-optimization


【解决方案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 上测试过,运行良好。

【讨论】:

    猜你喜欢
    • 2022-01-22
    • 1970-01-01
    • 2014-07-31
    • 1970-01-01
    • 2023-03-23
    • 2019-08-01
    • 2014-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多