【问题标题】:How to insert a sequential number on the same insert in a sequence?如何在序列中的同一插入上插入序列号?
【发布时间】:2018-09-02 18:01:01
【问题描述】:

如何在表中插入一个数字,该数字是来自同一 FK 的记录数加 1。

解释: 有一个表格将保存阶段数(1,2,3 ...)。 创建新阶段时,我想让列号成为已存在阶段的数量之和。

我尝试使用 COUNT

在 planId 204 上,将有 3 个阶段。 在 html 表单上,我只想获取名称和年份。用户不对阶段的数量负责。添加时为序号。

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

【问题讨论】:

    标签: php mysql insert


    【解决方案1】:

    您可以在INSERT 上使用trigger 实现此目的:

    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)
    

    这将在INSERT 之前找到number 的最大值,将idPlan 的值加1,然后插入该值。在iDPlan 值没有条目的情况下,COALESCE(MAX(number),0) 将返回 0,因此将插入 1。

    例如在一张空桌子上

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

    输出:

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

    【讨论】:

    • 嗨 Renan,这有帮助吗?如果没有,您能否提供更多信息来帮助解决问题?
    猜你喜欢
    • 2019-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-25
    • 2013-05-30
    • 2011-06-30
    • 2020-11-04
    相关资源
    最近更新 更多