简体   繁体   中英

Max 3 rows in table for each user

Is it possible to make a script without else/if that deletes the oldest row for a user if the new row is the 4 row for that specific user?

I have a table called points_history. Fields are:

date(datetime), fk_player_id(int), points(int)

Here is my insert:

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

The reason for this taht I want to be able to go back in the players history and check points, but only the last 3 points and don't want a table with a million of rows.

Can it be done in one sql query?

Hoping for help and thanks in advance :-)

This is quite easy to do if you add a primary key to your table points_history .

Part 1:
Use the following script to add a primary key called points_history_id to your table:

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;

This needs to be run only once!

Part 2:
Now you can use the following SQL script to add a new record and delete the outdated:

-- 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;

If you use a database supporting transactions, I strongly recommend to wrap this script in a transaction. I tested it on MySQL 5.5.29 and it runs fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM