Question

How can I query one table just for sort order, but only get unique id's in order from another table?

I only wan't the unique book id form this query if possible. this is a one to many relationship, so there are many authors to one book, and thus the reason why I wen't with UNION ALL.

here's the query I came up with, but I keep getting Unknown column 'a.author_name' in 'field list'

SELECT b.id FROM books AS b
UNION ALL
SELECT a.book_id, FROM authors AS a
ORDER BY a.author_name DESC; 

any help with this would be greatly apreceated

Was it helpful?

Solution 2

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;

OTHER TIPS

If you are using UNION then the columns specified in ORDER BY clause must be present in SELECT clause. Based on your requirement, you can get ONLY id with join

SELECT b.id FROM books AS b 
inner join authors AS a ON a.book_id=b.bid
ORDER BY a.author_name DESC; 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top