mysql - 如何将 mysql 查询转换为 sequelize?

标签 mysql sequelize.js

测试表

p_id   p_type   name
----------------------------------
100    Y        hong
101    Y        kim
200    N        park
201    N        John

我想在测试表中插入“102 Y choi”。

mysql查询

insert into test(p_id,p_type,name) 
select (max(p_id)+1),'Y','choi' from test where p_type='Y'

sequelize 中的等效查询是什么?

最佳答案

除了在事务中进行两次查询外,我看不到任何其他选项:

sequelize.transaction(t => {
  Test.findAll({
    order: [['p_id', 'DESC']],
    where: { p_type: 'Y' },
    limit: 1
  }, {transaction: t}).then(maxTest=>{
    const max = (maxTest[0] || {p_id: 0}).p_id + 1;
    return Test.create({
        p_id: max,
        p_type: 'Y',
        name: 'choi'
    }, {transaction: t})
  })
})

关于mysql - 如何将 mysql 查询转换为 sequelize?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51446280/

相关文章:

node.js - 使用 Sequelize 共享单个数据库的多个 Web 服务

node.js - 从 Sequelize 中的 Promise 内部中断 for 循环

mysql - 通过更新外键来更新主键

mysql - 删除数据库中表中的多个列。 ( rails )

mysql - 序列化具有相同外键的多条记录的连接表

javascript - 无法使用 Multer 将文件从 React 上传到 Express(req.file 不显示任何内容,req.body 没问题)

mysql - 时差返回 NULL

MySQL 服务器已经消失! Big Headace - Windows 2003 和经典的 asp

php - SQL 语法错误 IN

mysql - 一对多sequelizejs ORM未能得到结果