mysql - mysql 选择加入第二行
问题描述
任务
task_id | content | date
-------------------------------
1 | task 1 | 2019-11-26
2 | task 2 | 2019-11-27
task_child
id | task_id | type | date_task
--------------------------------
1 | 1 | A | 2019-11-26
2 | 1 | B | 2019-11-27
3 | 1 | A | 2019-11-28
4 | 1 | B | 2019-11-28
5 | 2 | A | 2019-11-26
6 | 2 | B | 2019-11-26
7 | 2 | C | 2019-11-28
嗨,我有两个如上所述的表,我如何加入该表才能从每个 task_child 中仅获取第二行?
结果应如下所示:
task_id | content | type | date_task
------------------------------------
1 | task 1 | B | 2019-11-27
2 | task 2 | B | 2019-11-26
解决方案
如果您正在运行 MySQL 8.0,则可以row_number()
在子查询中使用相同的组中的子表中的记录进行排名task_id
,并将其用作连接过滤器:
select t.task_id, t.content, c.type, c.date_task
from task t
inner join (
select c.*, row_number() over(partition by task_id order by date_task) rn
from task_child
) c on c.task_id = t.task_id and c.rn = 2
在早期版本中,这有点复杂。一种解决方案是使用子查询添加连接条件,以确保子表中只有一条记录与当前正在连接的记录相同task_id
且更早:date_task
select t.task_id, t.content, c.type, c.date_task
from task t
inner join task_child c
on c.task_id = t.task_id
and (
SELECT count(*)
from task_child c1
where c1.task_id = c.task_id and c1.date_task < c.date_task
) = 1
推荐阅读
- typescript - 错误:“导航器”类型上不存在属性“通知”
- python - 如何在 Python 2.7 中没有公共键的两个列表的元素之间执行算术运算
- arrays - 如何以模态显示照片?
- php - 如何使用 PHP 代码验证引导模式?
- javascript - 动态控制器未启动
- asp.net-mvc - 删除并上传新图像后显示旧图像
- ruby - 捕获 table_print 的输出
- reactjs - 如何使用 React 禁用 Tab 组件(Carbon 设计系统)
- excel - 有没有办法“真正”动态验证 VBA 中的两个不同的单元格值?
- c++ - 与在头文件中声明并在源文件中定义的外部数组链接时出现问题