mysql - 如何编写这些复杂的 MySQL 查询?
问题描述
我有以下 2 个表:
表“船长”
ID | 姓名 |
---|---|
1 | 队长1 |
2 | 队长2 |
3 | 队长3 |
4 | 队长4 |
5 | 队长5 |
6 | 队长6 |
7 | 队长7 |
8 | 队长8 |
9 | 队长9 |
10 | 船长10 |
表“远征”
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 |
队长9 | 3 |
队长8 | 3 |
解决方案
这是几个步骤:获取每个字幕的计数,获取最大计数,仅显示最大计数的船长。
一种典型的方法是使用窗口函数(自 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
);
推荐阅读
- c - 数组初始化时指针类型不兼容
- r - 如何执行线性回归而不出错?
- pine-script - 如何在多个柱满足条件后编写买入或卖出触发器,在我的情况下是高于某个 EMA 的 2 个 renko 柱
- scheme - 如何修复列表中关闭对的总和的错误
- javascript - 来自动画滑动菜单的 DIV 动画运动消失在 BODY 或 WRAPPER 后面?
- c++ - 在类的构造函数中初始化映射时如何避免内存泄漏?
- r - 使用 purrr 函数和 %>% 有效地从复杂 JSON 中提取嵌套数据帧
- android - 删除图像视图周围的空白
- machine-learning - 我是否需要同时执行网格搜索(使用交叉验证)和交叉验证方法?
- database - 数据库约束检查值(来自不同行)是否按连续顺序排列