【发布时间】:2021-09-13 23:07:23
【问题描述】:
我有一个使用 INNER JOINS 的 Sequelize 查询。问题是 sequelize 在内部添加了另一个 where 子句和子表上的子查询。那正在消耗查询性能。下面是我的代码示例和原始查询输出。
有没有办法让 sequelize 跳过添加这个 where 子句?
续集版本:6.x
PostModel.findAll({
where: {
id: 1,
},
include: [
{
model: CommentsModel,
required: true,
}
]
})
查询构建如下 SQL 查询。
SELECT "post".*
FROM (SELECT "post"."*"
FROM "posts" AS "post"
WHERE "post"."id" = 2
AND (SELECT "post_id"
FROM "comments" AS "c"
WHERE "comments"."post_id" = "post"."id" AND ("c"."text_search" @@ 'who:*')) IS NOT NULL
ORDER BY "post"."id" DESC
LIMIT 50 OFFSET 0) AS "post"
LEFT OUTER JOIN "post_tags" AS "tags" ON "post"."id" = "tags"."post_id"
LEFT OUTER JOIN "tag" AS "tags->tag" ON "tags"."tag_id" = "tags->tag"."id"
INNER JOIN "comments" AS "c" ON "post"."id" = "c"."post_id" AND ("c"."text_search" @@ 'who:*')
ORDER BY "post"."id" DESC;
如您所见,WHERE 子句新增了一个
(SELECT "post_id"
FROM "comments" AS "c"
WHERE "comments"."post_id" = "post"."id" AND ("c"."text_search" @@ 'who:*'))
这基本上是在扼杀查询的性能。
【问题讨论】:
-
根据sequelize.org/master/manual/… 应该是
required: true而不是require: true -
感谢您的指出。但问题依然存在。
标签: sql node.js postgresql sequelize.js