一尘不染

MySQL:从具有COUNT()的子查询中选择MAX()

sql

在将其标记为重复之前,请先看一下此SQLFiddle

我有这个架构:

CREATE TABLE book(book_id int,
                   book_name varchar(100),
                   author_id int,
                   editor_id varchar(100),
                   isbn varchar(100));
INSERT INTO book
VALUES
(1 , 'Book1 Title' ,  12  ,  'Editor1'   , '8000-9000' ),
(2 , 'Book2 Title' ,  98  ,  'Editor1'   , '8000-9001' ),
(1 , 'Book1 Title' ,  12  ,  'Editor1'   , '8000-9002' ),
(3 , 'Book3 Title' ,  3  ,  'Editor1'   , '8000-9003' );

CREATE TABLE author(author_id int,
                    fn varchar(100),
                    ln varchar(100));
INSERT INTO author
VALUES
(12, 'name1','lname1'),
(98,'name2','lname2'),
(3,'name3','lname3');

子查询:

  SELECT c.author_id,COUNT(*) book_count FROM book c
  GROUP BY c.author_id

结果:

| AUTHOR_ID | BOOK_COUNT |
--------------------------
|         3 |          1 |
|        12 |          2 |
|        98 |          1 |

现在,这里最棘手的部分是此查询的结果:

SELECT MAX(book_count),a.* FROM
author a,(
  SELECT c.author_id,COUNT(*) book_count FROM book c
  GROUP BY c.author_id
) b 
where a.author_id = b.author_id

这是:

| MAX(BOOK_COUNT) | AUTHOR_ID |    FN |     LN |
------------------------------------------------
|               2 |         3 | name3 | lname3 |

应该是这样的:

| MAX(BOOK_COUNT) | AUTHOR_ID |    FN |     LN |
------------------------------------------------
|               2 |        12 | name1 | lname1 |

您认为查询中有什么问题?


阅读 168

收藏
2021-03-08

共1个答案

一尘不染

而不是MAX()您可以简单地使用LIMIT相同。也可以JOIN改用。

SELECT book_count,a.author_id,a.fn, a.ln 
FROM author a
JOIN
(
  SELECT c.author_id,COUNT(*) book_count FROM book c
  GROUP BY c.author_id
) b 
ON a.author_id = b.author_id
ORDER BY book_count DESC LIMIT 1

输出:

| BOOK_COUNT | AUTHOR_ID |    FN |     LN |
-------------------------------------------
|          2 |        12 | name1 | lname1 |

看到这个SQLFiddle


编辑:

如果要使用MAX()它,则必须使用如下子查询:

SELECT book_count,a.author_id,a.fn, a.ln 
FROM author a
JOIN
(
  SELECT c.author_id,COUNT(*) book_count FROM book c
  GROUP BY c.author_id
) b 
ON a.author_id = b.author_id
WHERE book_count = 
        (SELECT MAX(book_count)
        FROM
        (
           SELECT c.author_id,COUNT(*) book_count FROM book c 
           GROUP BY c.author_id
        ) b )

看到这个SQLFiddle


编辑2:

除了LIMIT在外部查询中使用之外,您也可以在内部查询中使用它:

SELECT book_count,a.author_id,a.fn, a.ln 
FROM author a
JOIN
(
  SELECT c.author_id,COUNT(*) book_count FROM book c
  GROUP BY c.author_id
  ORDER BY COUNT(*) DESC LIMIT 1
) b 
ON a.author_id = b.author_id

看到这个SQLFiddle

2021-03-08