TransWikia.com

How to insert values in mysql taking previous row into account

Database Administrators Asked by F79 on December 6, 2021

I have this table, players, with the following columns:

  • id
  • name
  • player_number
  • round

and I would like to auto fill the player_number (1 and 2) and increment the round when inserting a new player 1.

How can I do this without having to retrieve last player and make a new query ?

When I insert a new player, if it has no player, make round 1 and player 1. When adding a new player it makes him player 2 and round 1. After this adding a new player makes player 1 and round 2 and so on…

One Answer

In any case you'll need some sort of sequence. As MySQL does not provide such things, as far as i know, the only resort is an AUTO_INCREMENT column. Put some in a table abused as a sequence. Than have a BEFORE INSERT FOR EACH COLUMN trigger on your game table. Inside it, insert into the sequence table, so that a new incremented value is created. Select the maximum value of the sequence table. You can now calculate your values for player end round:

Let v be the selected value from the sequence table. Then the player p = (v - 1) mod 2 + 1 and the round r = ceil(v / 2).

But be aware, that deleting rows from your games table will not reset the sequence table. The pattern will continue on where it left the last time an insert into the games table was made.

Example:

CREATE TABLE game (id INTEGER AUTO_INCREMENT,
                   player INTEGER,
                   round INTEGER,
                   PRIMARY KEY (id));

CREATE TABLE game_sequence
             (value INTEGER AUTO_INCREMENT,
              PRIMARY KEY (value));

DELIMITER $$
CREATE TRIGGER game_ai
               BEFORE INSERT
               ON game
               FOR EACH ROW
BEGIN
  DECLARE _value
          INTEGER;

  INSERT INTO game_sequence
              VALUES ();

  SELECT max(value) INTO _value
         FROM game_sequence;
  SET NEW.player = (_value - 1) % 2 + 1;
  SET NEW.round = ceil(_value / 2);
END;
$$

DELIMITER ;

Answered by sticky bit on December 6, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP