【问题标题】:Translate SQL into knex将 SQL 翻译成 knex
【发布时间】:2019-11-03 04:12:02
【问题描述】:

我正在使用 knex 和 objection 来制作 API。我试图在不使用 raw 的情况下将下面的 SQL 转换为 knex,这样我就可以获得与组和其他用户列表相关联的所有帖子。数据分布在 4 个表组、帖子、投票和朋友中。

select posts.*, sum(voted.vote), users.full_name
        from  users, posts left outer join voted
        on posts.id = voted.post_id
        where(users.id = posts.user_id and posts.group_id = ${group_id})
        group by posts.id, voted.post_id, users.full_name;`);
console.log(post.rows[0], 'post from rows

【问题讨论】:

  • 你尝试了什么?

标签: node.js postgresql express knex.js


【解决方案1】:

你很好:这个 SQL 没有什么不寻常的地方,所有这些都可以使用 Knex API 来表示。但是,表达隐式连接是有意义的:

FROM users, posts

作为显式连接:

FROM users
JOIN posts ON users.id = posts.user_id

意味着您可以删除WHERE 子句的第一部分。它看起来有点像这样:

knex
  .select("posts.*", "users.full_name")
  .sum("voted.vote")
  .from("users")
  .join("posts", "posts.user_id", "users.id")
  .leftOuterJoin("voted", "posts.id", "voted.post_id")
  .where("posts.group_id", groupId)
  .groupBy("posts.id")
  .groupBy("voted.post_id")
  .groupBy("users.full_name")

这会产生 SQL 输出:

'select "posts".*, "users"."full_name", sum("votes"."vote") from "users" ' +
    'inner join "posts" on "posts"."user_id" = "users"."id" left outer ' +
    'join "voted" on "posts"."id" = "voted"."post_id" where ' +
    '"posts"."group_id" = ? group by "posts"."id", "voted"."post_id", ' +
    '"users"."name"'

您可能还会发现您的一些GROUP BYs 是不必要的,但看看你是怎么做的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-07
    • 2019-05-09
    • 2014-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多