我在MySQL数据库中有一个包含Title和Author列的书籍表。我需要选择所有书籍中包含超过X本书的作者的书籍。
以下是所需输出的示例:
| Author | Title |
|---------------|----------------------|
| Dan Brown | Angels and Demons |
| Dan Brown | The Da Vinci Code |
| Robert Ludlum | The Bourne Identity |
| Robert Ludlum | The Bourne Supremacy |
每个作者可以使用一个简单的小组获得一本书并具有条件:
SELECT * FROM books
GROUP BY author
HAVING count(author) > 1
ORDER BY author;
其中给出了以下输出:
| Author | Title |
|---------------|----------------------|
| Dan Brown | Angels and Demons |
| Robert Ludlum | The Bourne Identity |
如何获得一本包含超过X本书的作者的书籍列表?
答案 0 :(得分:3)
您可以将查询用作sub-select:
SELECT * FROM books WHERE Author IN (
SELECT Author
FROM books
GROUP BY Author
HAVING COUNT(Author) > 1
) ORDER BY Author, Title;
如果您想获得每位作者的简单(逗号分隔)书籍列表,您还可以使用GROUP_CONCAT
使用以下解决方案:
SELECT Author, GROUP_CONCAT(Title) AS title_list
FROM books
GROUP BY Author
HAVING COUNT(Author) > 1
ORDER BY Author;
答案 1 :(得分:2)
您应该可以使用subquery:
SELECT * FROM books
WHERE author IN (
SELECT author
FROM books
GROUP BY author
HAVING COUNT(author) > 1
)
答案 2 :(得分:1)
也许尝试使用in ...
SELECT [Author] , [Title]
FROM [books] b
where [Author] in
(select Author from [books] group by [Author]
having count(Author) >1)
答案 3 :(得分:0)
一个非常简单的查询将如下所示
SELECT books.Title
FROM (SELECT Count(books.Author) AS CountOfAuthor, books.Author AS A
FROM books
GROUP BY books.Author ) AS bookByAuthor INNER JOIN books ON bookByAuthor.A =
books.Author
WHERE (((books.Author)=[bookByAuthor].[A]));
希望这会有所帮助