提问人:Suleyman 提问时间:11/10/2023 更新时间:11/10/2023 访问量:20
在 Sequelize.js 中包含的模型上使用聚合函数中的 case-when
Using case-when in aggregate function on included model in Sequelize.js
问:
灵感来自答案:在 Sequelize.js 的聚合函数中使用 case-when 我想根据我拥有的类型在多个案例上聚合。SUM
这是我要转换为的查询原始数据:MySQL
Sequelize
SELECT
article.*,
SUM(case when isLike = TRUE then 1 else 0 end) likes,
SUM(case when isLike = FALSE then 1 else 0 end) dislikes
FROM article
LEFT JOIN articleLike ON articleLike.articleId = article.id
group by article.id
order by article.id;
我已经在 Sequelize 中尝试了很多东西,在我的选项中也添加了 paginaton,我最接近的答案是:
await Article.findAll({
include: [
{
model: ArticleLike,
as: "likes",
attributes: []
},
],
attributes: [
[
Sequelize.fn(
"SUM",
Sequelize.literal("CASE WHEN likes.isLike = TRUE THEN 1 ELSE 0 END")
),
"nbLikes",
],
[
Sequelize.fn(
"SUM",
Sequelize.literal(
"CASE WHEN likes.isLike = FALSE THEN 1 ELSE 0 END"
)
),
"nbDislikes",
],
],
offset: 0,
limit: 9,
group: "id",
order: [["id"]],
});
然而,它不起作用并给我错误:
Unknown column 'likes.isLike' in 'field list'
抛出错误之前默认生成的 SQL 查询:
Executing (default):
SELECT `article`.*
FROM (SELECT `article`.`id`, SUM(CASE WHEN likes.isLike = TRUE THEN 1 ELSE 0 END) AS `nbLikes`, SUM(CASE WHEN likes.isLike = FALSE THEN 1 ELSE 0 END) AS `nbDislikes` FROM `article` AS `article` GROUP BY `id` ORDER BY `article`.`id` LIMIT 0, 9) AS `article`
LEFT OUTER JOIN `articleLike` AS `likes` ON `article`.`id` = `likes`.`articleId`
ORDER BY `article`.`id`;
奇怪的是,如果我的选项对象中不存在并且不存在,我的 Sequelize 请求就会起作用。limit
offset
以下作品(不含所有属性):article
await Article.findAll({
include: [
{
model: ArticleLike,
as: "likes",
attributes: []
},
],
attributes: [
[
Sequelize.fn(
"SUM",
Sequelize.literal("CASE WHEN likes.isLike = TRUE THEN 1 ELSE 0 END")
),
"nbLikes",
],
[
Sequelize.fn(
"SUM",
Sequelize.literal(
"CASE WHEN likes.isLike = FALSE THEN 1 ELSE 0 END"
)
),
"nbDislikes",
],
],
// none of limit and offset
group: "id",
order: [["id"]],
});
这给了我下面的结果:
--- 0 // article 0 with his num of likes dislikes
nbLikes "2"
nbDislikes "1"
--- 1 // article 1 with his num of likes dislikes
nbLikes "2"
nbDislikes "1"
--- 2 // article 2 with his num of likes dislikes
nbLikes "2"
nbDislikes "1"
有人可以帮我弄清楚吗?
答: 暂无答案
评论