2

我发现的这个问题让我发疯,(编辑:)因为我试图在没有按方法排序的情况下实现这一目标。我有一张桌子:

BookAuthors(书,作者)

book     author
------ ---------
1        Joy McBean
2        Marti McFly
2        Joahnn Strauss
2        Steven Spoilberg
1        Quentin Toronto
3        Dr E. Brown

书籍和作者都是关键。

现在我想选择不同“作者”数量最多的“书”值,以及作者的数量。在我们的例子中,查询应该检索有 3 个作者的“书”2。

book        authors
-------- ------------
2            3

我已经能够将它们分组并使用此查询获取每本书的作者数量:

select B.book, count(B.author) as authors
from BookAuthors B
group by B.book

这将导致:

book        authors
-------- -------------
1              2
2              3
3              1

现在我只想获得作者数量最多的书。这是我尝试过的查询之一:

select Na.libro, Na.authors from (
    select B.book, count(B.author) as authors
    from BookAuthors B
    group by B.book
    ) as Na
where Na.authors in (select max(authors) from Na)

select Na.libro, Na.authors from (
    select B.book, count(B.author) as authors
    from BookAuthors B
    group by B.book
    ) as Na
having max( Na.authors)

我有点挣扎……

感谢您的帮助。

编辑:由于@Sebas 很乐意回答正确并扩展我的问题,因此我想到了使用 CREATE VIEW 方法的解决方案:

create view auth as
    select A.book, count(A.author)
    from BooksAuthors A
    group by A.book
;

进而

select B.book, B.nAuthors
from auth B 
where B.nAuthors = (select max(nAuthors)
                    from auth)
4

3 回答 3

1
SELECT cnt.book, maxauth.mx
FROM (
    SELECT MAX(authors) as mx
    FROM 
        (
            SELECT book, COUNT(author) AS authors 
            FROM BookAuthors 
            GROUP BY book
        ) t
    ) maxauth JOIN 
        (
            SELECT book, COUNT(author) AS authors 
            FROM BookAuthors 
            GROUP BY book
        ) cnt ON cnt.authors = maxauth.mx

该解决方案将更加美观和高效,具有以下观点:

CREATE VIEW v_book_author_count AS 
    SELECT book, COUNT(author) AS authors 
    FROM BookAuthors 
    GROUP BY book
;

进而:

SELECT cnt.book, maxauth.mx
FROM (
    SELECT MAX(authors) as mx
    FROM v_book_author_count 
    ) maxauth JOIN v_book_author_count AS cnt ON cnt.authors = maxauth.mx
;
于 2013-11-03T02:40:03.240 回答
0
select book, max(authors)
from ( select B.book, count(B.author) as authors 
    from BookAuthors B group by B.book ) 
table1;

我无法尝试这个,因为我没有 mysql……你试着让我知道……

于 2013-11-03T02:35:07.470 回答
0
SELECT book b, COUNT(author) c 
FROM BookAuthors
GROUP BY b
ORDER BY c DESC LIMIT 1;
于 2013-11-03T02:37:19.323 回答