gpt4 book ai didi

mysql 选择加入第二行

转载 作者:行者123 更新时间:2023-11-29 15:26:26 25 4
gpt4 key购买 nike

任务

task_id |  content | date
-------------------------------
1 | task 1 | 2019-11-26
2 | task 2 | 2019-11-27

任务子级

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_iddate_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

关于mysql 选择加入第二行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59045456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com