0

SQL query to get list of Authors who have written at least a book on all Genres

Tables are

      Author_id  |  Author_info  => authors
      Genre_id   |  Genre_info   => genres
      Author_id  |  Genre_id  |  Book_id  => books

I'm using Mysql, what would be the best way to do this?

5
  • What did you try, what results did it gave you ? Commented Nov 18, 2011 at 9:18
  • Have you tried something yourself already? As a tip, start by finding authors where there is a gender that they have NOT written about. Those are the authors that you DON'T want. Commented Nov 18, 2011 at 9:19
  • My idea was counting the number of genres from 'genres' and then matching them with distinct mapping of (author_id,genre_id), but as I have been away from SQL for a while, I couldn't put it together in SQL Commented Nov 18, 2011 at 9:25
  • This is a good approach as well and it will probably be faster. The answer from Thilo is nice and does exactly this. Commented Nov 18, 2011 at 9:49
  • yes it is what i could do in English but needed someone like Thilo to put down as SQL Commented Nov 18, 2011 at 9:52

4 Answers 4

2

If N is the number of distinct genres:

select author_id, count(distinct genre_id) as genres
from books 
group by author_id 
having genres = N
Sign up to request clarification or add additional context in comments.

Comments

1

Assumed database schema as this

authors
|-  Author_id  -|- Author_info -|
genres
|-  Genre_id   -|- Genre_info  -|
books
|-  Author_id  -|-  Genre_id   -|-  Book_id -|

Query

SELECT authors.Author_id
FROM authors
LEFT INNER JOIN books ON (authors.Author_id = books.Author_id)
GROUP BY authors.Author_id
HAVING COUNT(DISTINCT books.Genre_id) = (SELECT COUNT(*) FROM genres)

1 Comment

Are you sure this will work? Looking at the SQL I think it will aggregate the count across all books for all authors as there is no grouping by author.
0

Try this:

SELECT Author_id
FROM books
INNER JOIN Genre USING (Genre)
GROUP BY Author_id
HAVING COUNT(Author_id) >= (SELECT COUNT(*) FROM Genre); 

Comments

0

For written at least a book on all Genres

Try...

select author_id, count(distinct genre_id) as genres
from books 
group by author_id 
having genres >= 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.