I have three tables:
1) book
Column Type | book_id | isbn | title | year |
book_id integer Auto Increment PK | 1 | 1234 | Book1 | 1999 |
isbn character varying(30) UNIQUE | 2 | 1235 | Book2 | 1999 |
title character varying(150) | 3 | 1236 | Book3 | 2009 |
year smallint
2) author
Column Type | author_id | name |
author_id integer Auto Increment PK | 5 | Joe Doe |
name character varying(100) | 7 | John Curry |
| 9 | Jim Webb |
| 11 | Carl Lee |
3) book_author
Column Type | book_id | author_id |
book_id integer REFERENCES book(book_id) | 1 | 5 |
author_id integer REFERENCES author(author_id) | 1 | 7 |
PRIMARY KEY (book_id, author_id) | 2 | 9 |
| 3 | 11 |
A book can have one or more authors so I decided to create the book_author table to connect the book and the author tables together. I want to create a query to select for example: the book title and author name(s) of all the books that have written in 1999. This query should return something like:
title name
Book1 Joe Doe
Book1 John Curry
Book2 Jim Webb
I have manage to create two queries that somehow achieve this purpose (well not quite).
SELECT name from author WHERE author_id =
ANY (SELECT author_id FROM book_author WHERE book_author.book_id = 1)
SELECT title FROM book WHERE book_id = ANY
(SELECT book_id FROM book_author WHERE author_id = 5 OR author_id = 7)
Can you provide me with a single query which achieves the above mention purpose. It would be nice if you explain the structure of the query, the reasoning behind it. Thank you in advance