首页 > 解决方案 > 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

标签: mysqlsqljoinselect

解决方案


如果您正在运行 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

推荐阅读