最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

如何为Sequelize转换SQL查询?

IT培训 admin 9浏览 0评论

如何为Sequelize转换SQL查询?

我有一个SQL查询(使用mysql作为DB),我现在需要在node.js中重写为sequelize.js查询。

SQL查询

SELECT p.UserID, SUM(p.score), u.username
FROM Picks p
LEFT JOIN Users u
ON p.UserId = u.id
GROUP BY p.UserId;

不太确定如何构造此查询以获得与sequ​​elize相同的结果。

回答如下:

这应该做你需要的:

db.Pick.findAll({
  attributes: [
    'UserID',
    [db.sequelize.fn('SUM', db.sequelize.col('score')), 'score']
  ],
  include: [{
    model: db.User,
    required: true,
    attributes: ['username']
  }],
  group: ['UserID']
}).then((results) => {
  ...
})

如何为Sequelize转换SQL查询?

我有一个SQL查询(使用mysql作为DB),我现在需要在node.js中重写为sequelize.js查询。

SQL查询

SELECT p.UserID, SUM(p.score), u.username
FROM Picks p
LEFT JOIN Users u
ON p.UserId = u.id
GROUP BY p.UserId;

不太确定如何构造此查询以获得与sequ​​elize相同的结果。

回答如下:

这应该做你需要的:

db.Pick.findAll({
  attributes: [
    'UserID',
    [db.sequelize.fn('SUM', db.sequelize.col('score')), 'score']
  ],
  include: [{
    model: db.User,
    required: true,
    attributes: ['username']
  }],
  group: ['UserID']
}).then((results) => {
  ...
})

与本文相关的文章

发布评论

评论列表 (0)

  1. 暂无评论