The simplest way if you need a unique book ID and yet you want to sort it based on the author's name (you say "there are many authors per book") is to use a SUBSELECT
with GROUP BY
.
In this case:
SELECT b.id
FROM books AS b
JOIN (
SELECT book_id, MAX(author_name) AS author_name
FROM authors GROUP BY book_id ) AS a
ON (b.id = a.book_id)
ORDER BY a.author_name DESC;
You can see a SQL Fiddle here.
Note that MAX(author_name)
is necessary if you sort in descending order. If you wanted to sort in ascending order, you'd need to use MIN()
.
CREATE TABLE books ( id integer, title varchar(32) );
CREATE TABLE authors ( book_id integer, author_name varchar(32) );
INSERT INTO books VALUES ( 1, 'The Book' );
INSERT INTO books VALUES ( 2, 'Book II');
INSERT INTO authors VALUES ( 1, 'First Author' );
INSERT INTO authors VALUES ( 2, 'Second Author' );
INSERT INTO authors VALUES ( 2, 'Third Author');
INSERT INTO authors VALUES ( 2, 'Another Author');
This yields first book II, since "Third Author" comes first in alphabetic descending order, then "The Book", for a total of two IDs.
If we were to add an author coming later than T to book 1,
INSERT INTO authors VALUES ( 1, 'Zaftig' );
...then the same query would return first book ID 1, then book ID 2.
Just adding a DISTINCT
to the straight INNER JOIN
might not work since it could reorder the id
's (you can see this in the fiddle by adding an author with name starting with Z):
SELECT DISTINCT b.id FROM books AS b
INNER JOIN authors AS a ON a.book_id=b.id
ORDER BY a.author_name DESC;