简体   繁体   中英

Increment a column based on its id in mysql

Im making a drag n drop sortable list. What I am trying to do is increment a column in MySql based on its id value automatically when new records are entered. ie:

  • if i have a row with an id = 3, and it is the first record enetered for that id, then its recordid = 1.
  • if i have a row with an id = 14, and it is the first record enetered for that id, then its recordid = 1.
  • if i have a row with an id = 3, and it is the second record enetered for that id, then its recordid = 2.

So i want it to autoincrement recordid based on its id value. not the whole table value. Does that make sence? what code would i need in php to find the highest value recordid pertaining to the id and then increment it by 1 when a new record is entered? Thanks in advance.

Something like this?

INSERT INTO `table` (`id`, `recordid`) VALUES
(
    $id,
    (SELECT MAX(`recordid`) + 1 AS `rid` FROM `table` WHERE `id` = $id)
);

You could probably optimize it way further though.

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