【问题标题】::Sequelize how set returned data order:Sequelize 如何设置返回数据的顺序
【发布时间】:2012-12-01 14:49:59
【问题描述】:

我已经使用限制和偏移量设置 findAll 查询的返回数据顺序,我使用的是文档中的示例代码:order: 'group DESC',但它会抛出错误提示:

Error: SQLITE_ERROR: near "group": syntax error

这是完整的功能。

A_Model.findAll({
     offset:req.query.page * req.query.rows - req.query.rows,
     limit :req.query.rows // TODO: Of course, I put the trailing comma here ;)
     // TODO: order: 'group DESC'
    })
.success(function (docs) {
    response_from_server.records = count;
    response_from_server.page = req.query.page;
    response_from_server.total = Math.ceil(count / req.query.rows);
    response_from_server.rows = [];

    for (item in docs) {
        response_from_server.rows.push({
            id  :docs[item].id,
            cell:[
                docs[item].group,
                docs[item].description,
                docs[item].path,
                docs[item].value
            ]
        });
    }

    // Return the gathered data.
    res.json(response_from_server);
})
.error(function (error) {       
    logger.log('error', error);
});

提前致谢。

【问题讨论】:

  • 一个 SQL group by 需要定义一个聚合函数来分组。看来你还没有定义一个。不确定 node.js 是否有能力进行聚合和分组。
  • @EricLeschinski:感谢您的评论。我最近从mongodb 转到SQLite,对SQL 知之甚少。你能给我举个例子吗?
  • @EricLeschinski:刚刚注意到:group 是数据库中的一列。也许是保留字?
  • 在 SQL 中,'group by' 不能独立存在。它必须具有聚合函数,例如,按组平均价格。不做聚合操作,分组是没有意义的。 w3schools.com/sql/sql_groupby.asp
  • @EricLeschinski:我真正想要的不是分组,而是按名为 group 的变量排序。

标签: node.js syntax-error sequelize.js


【解决方案1】:

您提供给 findAll 方法的“order”字符串在 Sequelize 中不会被解析,只是为了防止 SQL 注入而转义。 "group" 是 most some SQL 方言中的保留关键字,因此查询无法运行。

要使其正常工作,只需将“组”列放入`'s,如下所示:

A_Model.findAll({
 offset:req.query.page * req.query.rows - req.query.rows,
 limit :req.query.rows,
 order: '`group` DESC'
})

【讨论】:

  • 在 PostgreSQL 中试过,应该是 order: 'group DESC' 即没有反引号。
猜你喜欢
  • 2017-04-13
  • 2013-07-22
  • 1970-01-01
  • 2021-04-05
  • 1970-01-01
  • 2015-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多