简体   繁体   中英

SQL query query

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?

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

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)

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

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM