In a MySQL database I have two tables linked in a join. One table contains people details and another book details. I want to search the databases for a particular author (principalWriter) and return all the co-authers (additionalWriters) they have worked with.
So I use
SELECT
books.additionalWriters,
people.name
FROM
books
INNER JOIN people ON books.principalWriter = people.personID
WHERE personID = 1;
And this returns each book the author has worked on with the additional writers ID.
However how can I then use these returned IDs to look up their respective names in the name table? Is there a single query I can do to accomplish this?
The problem here is not the query itself but rather the database design. You should have this tables:
Writers(*ID*, name): Will store all writers (principal or not)Books(*ID*, name): Will store all booksWriters_Books(*WriterID*, *BookID*, Principal): This will store the relationship between the writers and the books and will specify if the writer for that book is principal or notPrimary keys are surrounded by asterisks
Note: You could also remove the Principal field and add it to the
Bookstable, but if a book happens to have to principal writers, you won’t be able to solve that with that schema.Once you update your design, the query will be much easier.