gpt4 book ai didi

MySql根据另一个表中的MAX值选择一个表中的所有行

转载 作者:搜寻专家 更新时间:2023-10-30 22:13:35 25 4
gpt4 key购买 nike

我希望能够从下面的表 1 和表 3 中获取所有数据,但除此之外,我还想从表 2 中获取最新的应用程序阶段。最新的应用程序阶段是通过获取最大 stage_date 来确定的每个应用程序。

表 1:应用

id | applicant_id | col_x | col_y | col_z
-----------------------------------------
10 300 a b c
11 310 a b c
12 320 a b c
13 330 a b c
14 340 a b c

表 2:application_progress

id | application_id | application_stage | stage_date | stage_notes
------------------------------------------------------------------
1 10 DRAFT 2013-01-01 (NULL)
2 10 APPLICATION 2013-01-14 (NULL)
3 10 PHASE1 2013-01-30 (NULL)
4 11 DRAFT 2013-01-01 (NULL)
4 12 DRAFT 2013-01-01 (NULL)
5 13 DRAFT 2013-01-01 (NULL)
6 14 DRAFT 2013-01-01 (NULL)
7 14 APPLICATION 2013-01-14 (NULL)

编辑:第三张表

表 3:申请人

id  | applicant_name | applicant_address | programme_id 
------------------------------------------------------
300 Applicant 1 abc 1
310 Applicant 2 xyz 2
320 Applicant 3 xyz 2
330 Applicant 4 xyz 2
340 Applicant 5 xyz 2

返回的数据集

applicant_id | applicant_name | current_stage
---------------------------------------------------------
300 Applicant 1 PHASE1
310 Applicant 2 DRAFT
320 Applicant 3 DRAFT
330 Applicant 4 DRAFT
340 Applicant 5 APPLICATION

我正在努力解决这个问题,希望得到任何帮助。

附言。试图举一个 sqlfiddle 的例子,但它现在已经失败了。如果在此之前没有答案,我会在它备份时用 sqlfiddle 更新它。

最佳答案

您可以使用相关子查询来做到这一点:

select a.*,
(select application_stage
from application_progress ap
where ap.application_id = a.id
order by stage_date desc
limit 1
) MostRecentStage
from applications a;

编辑:

你可以用这样的东西加入申请人数据::

select a.*, aa.*,
(select application_stage
from application_progress ap
where ap.application_id = a.id
order by stage_date desc
limit 1
) MostRecentStage
from applications a join
applicant aa
on a.applicant_id = aa.id;

关于MySql根据另一个表中的MAX值选择一个表中的所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18790011/

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