【问题标题】:Sequelize Aggregate count function returns wrong value with where clauseSequelize 聚合计数函数使用 where 子句返回错误值
【发布时间】:2020-09-19 00:51:27
【问题描述】:

我在 postgresql 中有两个表 - 系统和条件。 所有条件都有一个系统ID。 所有条件都会有一个字段“publishedStatus”

我的任务是获取所有具有相关“已发布”条件计数的系统。

以下是我的查询。

const allSystem = await db.System.findAll({
                subQuery: false,
                attributes: ["id", "title", [db.sequelize.fn("COUNT", db.sequelize.col("conditions.systemID")), "conditionsCount"]],
                include: [{
                    model: db.Condition,
                    as: "conditions",
                    attributes: [],
                    where: { publishedStatus: "published" },
                }],
                group: ['System.id', 'conditions.systemID'],
            });

当我在 'include' 中使用 'where' 子句时 -> 具有 0 'published' 条件的系统将被忽略。

而如果我删除 'where' 子句 -> 包含 0 个条件的系统。但它包括所有已发布状态的条件

结果供参考:

Background:
System 1 has 10 conditions. 8 published and 2 unpublished
System 2 has 4 conditions. 0 published and 4 unpublished
System 3 has 0 conditions. 0 published and 0 unpublished

Expected Result:
System 1 = 8 conditions
System 2 = 0 conditions
System 3 = 0 conditions

Without Where Clause:
System 1 = 10 conditions
System 2 =  4 conditions
System 3 =  0 conditions

With Where Clause: (Only 1 row is returned)
System 1 = 8 conditions

如何实现我想要的结果?请帮忙。

【问题讨论】:

    标签: postgresql sequelize.js


    【解决方案1】:

    您需要 required: false 才能使用 OUTER JOIN 来包含空条件。

    const allSystem = await db.System.findAll({
                subQuery: false,
                attributes: ["id", "title", [db.sequelize.fn("COUNT", db.sequelize.col("conditions.systemID")), "conditionsCount"]],
                include: [{
                    model: db.Condition,
                    as: "conditions",
                    attributes: [],
                    where: { publishedStatus: "published" },
                    required: false  // <-------------
                }],
                group: ['System.id', 'conditions.systemID'],
            });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-28
      • 1970-01-01
      • 2020-01-07
      相关资源
      最近更新 更多