【问题标题】:Auto-increment based on two columns in Sequelize for postgres基于 Sequelize for postgres 中的两列的自动增量
【发布时间】:2019-05-20 21:07:04
【问题描述】:

我想在 postgres 中存储学生数据如下, 其中卷号应根据批次自动增加。

我想知道如何在 Sequelize 中实现这一点。

id       batch         rollno      name
---------------------------------------------------------------
1         A             1000        John
2         A             1001        Javed
3         A             1002        Jake
4         B             1000        Jose
5         B             1001        James
6         A             1003        Jerry

这是我创建的模型。

var Student = sequelize.define('student', {
    id: {
        type: DataTypes.INTEGER(11),
        allowNull: false,
        primaryKey: true,
        autoIncrement: true
    },
    batch: {
        type: DataTypes.STRING,
        allowNull: false,
    },
    rollno: {
        type: DataTypes.INTEGER(11),
        allowNull: true,
        autoIncrement: true,
    },
    name: {
        type: DataTypes.STRING,
        allowNull: true,
    }
};

【问题讨论】:

    标签: node.js database postgresql sequelize.js


    【解决方案1】:

    您不能使用常规的自动增量来执行此操作,因为这将需要每个批次的不同顺序。您可以编写一个在插入时触发的触发器,并在表中查询批处理中当前的最大 rollno 并加 1,但这可能不是一个好主意。

    您可以做的是在运行查询时计算 rollno:

    CREATE TABLE test (
      id serial,
      batch text
    );
    
    INSERT INTO test (batch) VALUES ('A');
    
    SELECT
      id,
      batch,
      999 + rank() OVER (PARTITION BY batch order by id) as rollno
    FROM test
    order by id
    

    https://www.db-fiddle.com/f/vbVpvhfpzuhxKqQfNWsQVc/0

    【讨论】:

      猜你喜欢
      • 2021-08-25
      • 2021-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-09
      • 2017-09-30
      • 2015-03-01
      • 1970-01-01
      相关资源
      最近更新 更多