简体   繁体   English

在mysql中根据其ID增加一列

[英]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. 我正在尝试做的是在输入新记录时根据其id值自动在MySql中增加一列。 ie: 即:

  • if i have a row with an id = 3, and it is the first record enetered for that id, then its recordid = 1. 如果我有一个id为3的行,并且它是为该ID设置的第一条记录,则其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. 如果我有一个id为14的行,并且它是为该ID设置的第一条记录,则其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. 如果我有一个id为3的行,并且它是为该ID设置的第二条记录,则其recordid = 2。

So i want it to autoincrement recordid based on its id value. 因此,我希望它根据其id值自动递增recordid。 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? 我需要什么代码在php中查找与id有关的最高值recordid,然后在输入新记录时将其递增1? 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. 您可能可以进一步优化它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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