D
D
Dmitry2014-08-10 04:31:58
SQL
Dmitry, 2014-08-10 04:31:58

SQL query from 3 tables with 2 binders - is this possible?

There are such entities - Book, Author, Rubric. A book can have several authors, a book can belong to several categories, an author can write many books. Given this, I designed the tables like this:
books - id, title
authors - id, name, surname
topics - id, title
linking tables
book_author - book_id, author_id book_topic
- book_id, topic_id
authors? I suspect that it will be a mixture of nested selects and several joins, but I can't seem to get it right.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
_
_ _, 2014-08-10
@AMar4enko

SELECT books.*, topics.id as topic_id, topics.title as author_title, authors.id as author_id, authors.name as author_name FROM books
LEFT JOIN book_author ON book_author.book_id = books.id
LEFT JOIN book_topic ON book_topic.book_id = books .id
LEFT JOIN authors ON book_author.author_id = authors.id
LEFT JOIN topics ON book_topic.topic_id = topics.id
Just keep in mind that with two authors and three categories in one book, you will get 6 result rows.

V
Vladimir Smirnov, 2014-08-15
@bobzer

Adding some magic to AMar4enko's answer:

SELECT books.title,
GROUP_CONCAT(distinct CONCAT(authors.surname, ' ', authors.name) SEPARATOR ', ') as autors,
GROUP_CONCAT(distinct topics.title ORDER BY topics.title ASC SEPARATOR ', ') as titles
FROM books
LEFT JOIN book_author ON book_author.book_id = books.id
LEFT JOIN book_topic ON book_topic.book_id = books.id
LEFT JOIN authors ON book_author.author_id = authors.id
LEFT JOIN topics ON book_topic.topic_id = topics.id
group by books.id

This SQL query solves the problem of duplicating books with multiple authors and multiple categories

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question