cristiancodreanu
Programmer
Hello
I am using associative tables in a database and I have problems when I have to simultaneously query multiple tables.
As a simplified sketch of what I mean, these tables are given:
books:
book_id, book_title, book_author
authors:
author_id, author_name
books_authors_assoc:
books_authors_assoc_id, book_id, author_id
pubhouses:
pubhouse_id, pubhouse_name
books_pubhouses_assoc:
books_pubhouses_id, book_id, pubhouse_id
Supposing I want to display all the books whose author name ends with "escu", ordered by, say, publishing house, I will write:
SELECT books.book_title, books.book_author, authors.author_name, pubhouses.pubhouse_name
FROM books, authors, books_authors_assoc, pubhouses, books_pubhouses_assoc
WHERE authors.author_name LIKE '%escu' AND
authors.author_id = books_authors_assoc.author_id AND
books_authors_assoc.book_id = books.book_id AND
books.book_id = books_pubhouses_assoc.book_id AND
books_pubhouses_assoc.pubhouse_id = pubhouses.pubhouse_id
ORDER BY pubhouses.pubhouse_name DESC;
The above query does it's job, but the joining of those 5 tables is too slow (not to mention the duplicate results, needing DISTINCT or GROUP BY - more time needed).
Please show me the way to optimize that query.
Thank you.
cc
I am using associative tables in a database and I have problems when I have to simultaneously query multiple tables.
As a simplified sketch of what I mean, these tables are given:
books:
book_id, book_title, book_author
authors:
author_id, author_name
books_authors_assoc:
books_authors_assoc_id, book_id, author_id
pubhouses:
pubhouse_id, pubhouse_name
books_pubhouses_assoc:
books_pubhouses_id, book_id, pubhouse_id
Supposing I want to display all the books whose author name ends with "escu", ordered by, say, publishing house, I will write:
SELECT books.book_title, books.book_author, authors.author_name, pubhouses.pubhouse_name
FROM books, authors, books_authors_assoc, pubhouses, books_pubhouses_assoc
WHERE authors.author_name LIKE '%escu' AND
authors.author_id = books_authors_assoc.author_id AND
books_authors_assoc.book_id = books.book_id AND
books.book_id = books_pubhouses_assoc.book_id AND
books_pubhouses_assoc.pubhouse_id = pubhouses.pubhouse_id
ORDER BY pubhouses.pubhouse_name DESC;
The above query does it's job, but the joining of those 5 tables is too slow (not to mention the duplicate results, needing DISTINCT or GROUP BY - more time needed).
Please show me the way to optimize that query.
Thank you.
cc