获取至少编写过所有类型书籍的作者列表的SQL查询
表是
Author_id | Author_info => authors
Genre_id | Genre_info => genres
Author_id | Genre_id | Book_id => books
我使用Mysql,最好的方法是什么?
答案 0 :(得分:2)
如果N是不同类型的数量:
select author_id, count(distinct genre_id) as genres
from books
group by author_id
having genres = N
答案 1 :(得分:1)
假定数据库架构为
authors
|- Author_id -|- Author_info -|
genres
|- Genre_id -|- Genre_info -|
books
|- Author_id -|- Genre_id -|- Book_id -|
查询
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)
答案 2 :(得分:0)
试试这个:
SELECT Author_id FROM books INNER JOIN Genre USING (Genre) GROUP BY Author_id HAVING COUNT(Author_id) >= (SELECT COUNT(*) FROM Genre);
答案 3 :(得分:0)
至少写一本关于所有类型的书
...试
select author_id, count(distinct genre_id) as genres
from books
group by author_id
having genres >= 1