【问题标题】:How do write this query correctly如何正确编写此查询
【发布时间】:2021-01-16 08:10:04
【问题描述】:

我正在尝试在 Sequelize 中执行此查询,但出现错误

查询

LineItem.findAll(
        {
            attributes: [
                "orderId",
                [fn("sum", col("quantity")), "quantity"]
            ],
            include: [{
                model: Order,
                as: "lineItems",
                attributes: ["invoiceId"]
            }],
            group: ["orderId"],
            raw: true
        });

错误

column \"lineItems.invoice_id\" must appear in the GROUP BY clause or be used in an aggregate function

【问题讨论】:

  • 您能否将相关模型添加到问题中?

标签: node.js typescript postgresql sequelize.js


【解决方案1】:

您有两个选择,但首先您必须回答这个问题:您的查询中是否需要 invoiceId 列?

如果你的答案是肯定的,试试吧:

LineItem.findAll({
  attributes: ['orderId', [fn('sum', col('quantity')), 'quantity']],
  include: [
    {
      model: Order,
      as: 'lineItems',
      attributes: ['invoiceId'],
    },
  ],
  group: ['orderId', 'invoiceId'],
  raw: true,
});

如果你的答案是否定的,试试看:

LineItem.findAll({
  attributes: ['orderId', [fn('sum', col('quantity')), 'quantity']],
  include: [
    {
      model: Order,
      as: 'lineItems',
    },
  ],
  group: ['orderId'],
  raw: true,
});

【讨论】:

  • 这个答案解决了你的问题吗?请接受此答案,这将对其他人有所帮助。 How to accept an answer?
  • 是的,我想要 invoiceId 列,所以我尝试了第一个选项,但它显示列 \"invoiceId\" 不存在
  • 可以发表格和模型的脚本吗?我需要了解你的结构。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-04
  • 2011-02-20
  • 2015-08-14
  • 1970-01-01
  • 2021-01-15
相关资源
最近更新 更多