使用 knex 在 MySQL 节点中进行多次计数和左连接

Multiple count and left joins in MySQL Node using knex

我正在尝试查询帖子并使用 'count' 来获取要显示的评论和点赞总数。我的查询如下所示

  const posts = await knex
    .from("posts")
    .select("posts.id as id", "posts.text", "posts.user_id")
    .leftJoin("comments", "comments.post_id", "posts.id")
    .count("comments.post_id as comments")
    .leftJoin("likes", "likes.post_id", "posts.id")
    .count("likes.post_id as likes")
    .groupBy("posts.id");

  res.send(posts);

但是,如果我排除评论或点赞并执行以下操作,我会得到不同的结果:

  const posts = await knex
    .from("posts")
    .select("posts.id as id", "posts.text", "posts.user_id")
    .leftJoin("comments", "comments.post_id", "posts.id")
    .count("comments.post_id as comments")
    .groupBy("posts.id");

  res.send(posts);

我觉得我做错了什么。链接多个 'count' 和 'leftJoins' 的正确方法是什么?

首先从SQL查询开始,然后将其转换为Knex。

正如@nbk 所说,当您在最终结果中加入评论时,每个 评论.

都会收到一行

一个选项是在 select 中使用子查询,查询将如下所示:

Select posts.id as id, posts.text, posts.user_id, 
(Select count(*) from comments where comments.post_id=posts.id) as comments,
(Select count(*) from likes where likes.post_id=posts.id) as likes,
From posts;

此查询可以转换为 Knex:

const posts = await knex
  .from('posts')
  .select(
    'posts.id as id',
    'posts.text',
    'posts.user_id',
    knex('comments')
      .count('*')
      .whereRaw('?? = ??', ['comments.post_id', 'posts.id'])
      .as('comments'),
    knex('likes').count('*').whereRaw('?? = ??', ['likes.post_id', 'posts.id']).as('likes')
  );