【问题标题】:KnexJS How to create multiple inner joinKnexJS 如何创建多个内连接
【发布时间】:2019-06-01 16:04:54
【问题描述】:

我需要将此 SQL 查询转换为 KnexJS 查询

SELECT
    Book.Title,
    Book.Number,
    Author.Name,
    Author_1.Name,
    Author_2.Name,
    Author_3.Name
FROM
    ((((Book)
INNER JOIN Author ON Book.AuthName = Author.Name)
INNER JOIN Author AS Author_1 ON Book.AuthName = Author_1.Name)
INNER JOIN Author AS Author_2 ON Book.AuthName = Author_2.Name)
INNER JOIN Author AS Author_3 ON Book.AuthName = Author_3.Name
WHERE Book.Title = "HelpMe" ORDER BY Book.Number;

我已经阅读了这里的文档https://knexjs.org/#Builder-join,但我几乎不明白如何使用给定的示例来满足我的需要,因为没有这样的多重内连接示例。

请帮帮我

【问题讨论】:

    标签: sql database query-builder knex.js


    【解决方案1】:

    Knex 连接是可链接的,所以你可以做这样的事情:

    knex
      .select('title', 'author1', 'author2')
      .from('books')
      .join('authors as author1', 'books.author_name', '=', 'author1.name')
      .join('authors as author2', 'books.author_name', '=', 'author2.name')
    

    我怀疑您的示例存在问题,因为您一遍又一遍地运行基本相同的比较。通常,您会使用一系列外键(author1idauthor2id)链接到 authors 表,或者更准确地说是连接表,因为这是多对多关系:

    knex
      .select('books.title', 'authors.name')
      .from('books')
      .join('books_authors', 'books.id', '=', 'books_authors.book_id')
      .join('authors', 'authors.id', '=', 'books_authors.author_id')
    

    这会获取本书的所有作者,无论有多少,但需要一个仅包含 id 的附加表:

    exports.up = knex =>
      knex.schema.createTable('books_authors', t => {
        t.integer('book_id').references('books.id')
        t.integer('author_id').references('authors.id')
      })
    
    exports.down = knex => knex.schema.dropTable('books_authors')
    

    每次将作者添加到一本书时,您还需要将图书的 ID 和作者的 ID 添加到连接表中,这样两者之间就存在关系。这样一来,每本书可以有一位作者或一百位作者。

    【讨论】:

    • 谢谢,没想到这么简单
    猜你喜欢
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 2014-10-28
    • 1970-01-01
    相关资源
    最近更新 更多