duanpanhuo0618 2018-09-02 18:01
浏览 75

如何在序列中的同一插入上插入序列号?

How can I insert a number on a table that is the count of records from the same FK plus 1.

An explanation: there is a table that will hold the number of phases (1,2,3...). When a new phase is created, I would like to make the column number being the sum of the number os the phases that already exists.

I tried using COUNT

On planId 204, There will be 3 phases. On the html form I only want to get the name and year. The user is not responsible for the number of the phase. It is a sequential number when it is added.

INSERT INTO 
        phase (
        idPlan,
        name,
        number,
        constructionYear
        )
        VALUES (
        204,
        'jj',
         HERE IS THE SEQUENTIAL NUMBER,
        2001
        )

CREATE TABLE `phase` (
 `idPhase` int(11) NOT NULL AUTO_INCREMENT,
 `idPlan` int(11) NOT NULL,
 `number` int(11) NOT NULL,
 `constructionYear` year(4) NOT NULL,
 `name` varchar(100) DEFAULT NULL,
 PRIMARY KEY (`idPhase`),
 KEY `idPlan` (`idPlan`),
 KEY `idPlan_2` (`idPlan`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
  • 写回答

1条回答 默认 最新

  • douhao8456 2018-09-02 21:46
    关注

    You can achieve this with a trigger on INSERT:

    CREATE TRIGGER `phase_insert`
    BEFORE INSERT ON `phase` FOR EACH ROW 
    SET NEW.number = (SELECT COALESCE(MAX(number),0)+1 FROM phase WHERE idPlan=NEW.idPlan)
    

    This will find the maximum value of number before an INSERT on that value of idPlan increment it by 1 and then insert that value. In the case where there is no entry for the iDPlan value, the COALESCE(MAX(number),0) will return 0 so 1 will be inserted.

    e.g. in an empty table

    INSERT INTO phase (idPlan, name, number, constructionYear)
        VALUES (204, 'jj', 0, 2001), (204, 'xx', 0, 2002);
    SELECT * FROM phase
    

    Output:

    idPhase     idPlan  number  constructionYear    name
    3           204     1       2001                jj
    4           204     2       2002                xx
    
    评论

报告相同问题?

悬赏问题

  • ¥15 echarts动画效果失效的问题。官网下载的例子。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加