mysql选择加入第二行
任务 任务组儿童mysql选择加入第二行,mysql,sql,join,select,Mysql,Sql,Join,Select,任务 任务组儿童 task_id | content | date ------------------------------- 1 | task 1 | 2019-11-26 2 | task 2 | 2019-11-27 您好,我有两个表,如上所述,我如何加入该表,以便从每个task_子项中只获得第二行 结果如下: id | task_id | type | date_task -------------------------------- 1 |
task_id | content | date
-------------------------------
1 | task 1 | 2019-11-26
2 | task 2 | 2019-11-27
您好,我有两个表,如上所述,我如何加入该表,以便从每个task_子项中只获得第二行
结果如下:
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_id | content | type | date_task
------------------------------------
1 | task 1 | B | 2019-11-27
2 | task 2 | B | 2019-11-26
希望这对您有所帮助。如果您运行的是MySQL 8.0,您可以在子查询中使用row\u number对组内具有相同任务\u id的子表中的记录进行排序,并将其用作联接筛选器:
SELECT
Task.task_id,
Task.content,
Task_Child.type,
Task.task_date
FROM
Task
INNER JOIN
Task_Child
ON
Task.task_id=Task_Child.task_id;
在早期版本中,这要复杂一些。一种解决方案是添加一个带有子查询的联接条件,以确保子表中只有一条记录具有相同的任务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
如果需要第二种状态,可以使用相关子查询:
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版本如何,这可能是最有效的方法。为了获得最佳性能,您需要一个关于task\u childtask\u id、id、type的索引。试试这个,然后告诉我这个方法是否有效。选择task.task\u id、task.content、task\u child.type、task\u child.task\u date from task、task\u child where task.task\u id=task\u child.task\u id和task\u child.id=2@twister,如果您不想使用id=2,您可以尝试使用row_number,然后在where条件中使用它。如何?有什么例子吗?参见:
select t.*,
(select tc.type
from task_child tc
where tc.task_id = t.task_id
order by tc.id
limit 1, 1
) as type
from task t;