sql - KnexJS 如何创建多个内部连接

标签 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;

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

请帮帮我

最佳答案

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 添加到连接表中,以便在两者之间存在关系。这样一来,每本书可以有一位或一百位作者。

关于sql - KnexJS 如何创建多个内部连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56408296/

相关文章:

ruby-on-rails - SQLite3::BusyException

php - 如果单击链接,此 PHP 代码应该如何过滤掉显示的 SQL 行?

ormlite - 使用 ORMLite 编写查询

php - Yii2 ActiveQuery join keep 返回不同的值

mysql - 使用两个表的主键的外键关系

mysql - 为什么 "insert or update "中的命令更新工作不正常?

SQLite3 终端输出格式 .width

sql - 如何在不使用TOP和子查询的情况下从表中获取第n高的工资?

mysql - 是否可以只对列应用一个唯一约束,同时定义其他约束?

安卓 Debug模式 :Is it possible to view raw query or in-built query build by queryBuilder for countOf?