如何编写这些复杂的 MySQL 查询?

How to write these complex MySQL queries?

我有以下 2 tables :

table 'captain'

id 姓名
1 队长1
2 队长2
3 captain3
4 captain4
5 队长5
6 captain6
7 船长7
8 captain8
9 captain9
10 队长10

table 'expedition'

id 数量 id_captain id_navire id_hero
1 1 1 10 8
2 2 2 1 5
3 3 1 8 3
4 4 10 9 6
5 5 5 7 4
6 6 6 5 4
7 7 7 3 7
8 8 8 2 8
9 9 9 1 3
10 10 1 4 2
11 11 6 3 1
12 12 8 6 1
13 13 5 8 6
14 14 4 9 9
15 15 3 10 4
16 16 10 2 2
17 17 9 3 3
18 18 8 7 7
19 19 9 8 10
20 20 7 2 2

我有这个查询:

指导探险次数最多的船长 在 SQL:

select id_captain, count(expedition.id) as expedition_count
  from expedition
  group by id_captain
  having expedition_count = max(expedition_count);

但没有成功。我希望结果是这样的:

姓名 expedition_count
队长1 3
captain9 3
captain8 3

这是几个步骤:获取每个字幕的计数,获取最大计数,仅显示具有最大计数的船长。

典型的方法是使用 window 函数(自 MySQL 8 起可用):

select id_captain, expedition_count
from
(
  select 
    id_captain,
    count(*) as expedition_count,
    max(count(*)) over () as max(expedition_count)
  from expedition
  group by id_captain
) analyzed
where expedition_count = max_expedition_count;

或子查询:

select id_captain, count(*) as expedition_count
from expedition
group by id_captain
having expedition_count = 
(
  select count(*)
  from expedition
  group by id_captain
  order by count(*) desc
  limit 1
);