7

I need to transform this SQL query to KnexJS query

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;

I have read the doc here https://knexjs.org/#Builder-join but I barely understood how to use the given example to meet my need because there is no example for such multiple inner join.

Help me please

1 Answer 1

17

Knex joins are chainable, so you can do this kind of thing:

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')

I suspect there's a problem with your example though, in that you're running basically the same comparison over and over again. Normally you would link to an authors table using a series of foreign keys (author1id, author2id) or more properly a join table since this is a MANY to MANY relationship:

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')

This grabs all the authors for the book, no matter how many there are, but requires an additional table consisting of only ids:

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')

Each time you add an author to a book, you'd also add the book's id and the author's id to the join table so that a relationship exists between the two. This way, each book can have one author or a hundred.

1
  • 1
    Thanks, didn't realize it would be so simple as that
    – Bens
    Commented Jun 2, 2019 at 16:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.