不带ORDER BY的嵌套选择的max()值

时间:2013-11-03 02:26:33

标签: mysql sql nested subquery

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

BookAuthors (书籍,作者)

book     author
------ ---------
1        Joy McBean
2        Marti McFly
2        Joahnn Strauss
2        Steven Spoilberg
1        Quentin Toronto
3        Dr E. Brown
书,作者都是关键。

现在我想选择这本书'具有最高数量的不同作者和作者的数量。 在我们的例子中,查询应该检索'书' 2有3位作者。

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)

3 个答案:

答案 0 :(得分: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
;

答案 1 :(得分:0)

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

我无法尝试这个,因为我没有和我一起使用mysql ...你试着让我知道......

答案 2 :(得分:0)

SELECT book b, COUNT(author) c 
FROM BookAuthors
GROUP BY b
ORDER BY c DESC LIMIT 1;