KnexJS 如何创建多个内连接

Ben*_*ens 3 sql database query-builder knex.js

我需要将此 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;
Run Code Online (Sandbox Code Playgroud)

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

请帮帮我

Ric*_*her 7

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')
Run Code Online (Sandbox Code Playgroud)

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

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')
Run Code Online (Sandbox Code Playgroud)

这将获取本书的所有作者,无论有多少作者,但需要一个仅包含 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')
Run Code Online (Sandbox Code Playgroud)

每次向一本书添加作者时,您还要将书的 id 和作者的 id 添加到连接表中,以便在两者之间存在关系。这样,每本书可以有一个作者或一百个作者。