【发布时间】: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
如何实现我想要的结果?请帮忙。
【问题讨论】: