【问题标题】:How to write these complex MySQL queries?如何编写这些复杂的 MySQL 查询?
【发布时间】:2021-09-10 21:57:44
【问题描述】:

我有以下 2 个表:

表'船长'

id name
1 captain1
2 captain2
3 captain3
4 captain4
5 captain5
6 captain6
7 captain7
8 captain8
9 captain9
10 captain10

表'远征'

id number 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);

但没有成功。我期待结果是这样的:

name expedition_count
captain1 3
captain9 3
captain8 3

【问题讨论】:

  • 你使用的是什么 MySQL 版本?
  • 这个:having expedition_count = max(expedition_count) 不能工作。在HAVING 子句中,您一次查​​看一个聚合行。对于该行,有一个 expedition_count,因此在该值 (max(expedition_count)) 上应用 MAX 并不能做太多事情。根据 DBMS,您将收到语法错误或 max(expedition_count) 仅解析为 expedition_count

标签: mysql sql count max


【解决方案1】:

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

一种典型的方法是使用窗口函数(自 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
);

【讨论】:

  • 感谢您的帮助,非常有用。
  • 我还有另外两个问题,我会在重新编辑问题时添加它们。我希望我能得到帮助,谢谢。
  • 谁能帮我解决另外两个问题?
  • 你应该提出这个单独的请求,显示你的尝试并解释你卡在哪里。
  • 这是查询 q2 能走多远:
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-25
  • 2016-04-23
  • 2015-08-04
  • 2015-03-28
  • 2012-11-30
相关资源
最近更新 更多