在 mysql 中 'join' 和 'max' 的好方法

Good way to 'join' and 'max' in mysql

我是一名网络开发人员,我对一个看似简单的查询有点迷茫...

重点是,我有一个“步骤”table,我可以在其中查看某个人可以在我的网站上载哪些文件。

我有一个 'upload' table,我可以在其中查看真正上传到服务器上的文档。

这里是 'step' table:

id bigint auto_increment primary key,
document_id bigint null,
etape_id int not null,
emplacement varchar(500) not null,
extension json null,
max_size int null,
creation datetime not null comment (DC2Type:datetime_immutable),
modification datetime not null,
required tinyint(1) not null,
contraintes json null

上传文件如下:

id int auto_increment primary key,
candidature_id bigint not null,
step_id bigint null,
path varchar(255) not null,
creation datetime not null,
modification datetime not null,
status tinyint(1) null,
nom_origine varchar(255) not null

这些 table 之间的关系 [ship] 在 step.id 和 upload.step_id

我的基本要求是:

select
  edu.id as id, ud.id as docUp, 
  ud.nom_origine as nomUD, ud.creation
from etape_document_uploade as edu
left join upload_document as ud 
  on edu.id = ud.etape_document_uploade_id and candidature_id = 12
where etape_id = 2

谁给我:

+--+-----+------------------------------------------+-------------------+
|id|docUp|nomUD |creation |

+--+-----+------------------------------------------+-------------------+
|6 |14 |confirm_mini2.png |2022-03-18 15:13:58|
|6 |20 |confirm_mini.png |2022-03-19 15:13:58|
|7 |15 |intervention_ch.png |2022-03-18 15:13:58|
|10|19 |2022-03-23 08-01-45.png|2022-03-23 11:30:28|
+--+-----+------------------------------------------+-------------------+

但我想要的是每 'id' 只出现一次,在这两条线之间有创造最大值所以:

+--+-----+------------------------------------------+-------------------+
|id|docUp|nomUD |creation |
+--+-----+------------------------------------------+-------------------+
|6 |20 |confirm_mini.png |2022-03-19 15:13:58|
|7 |15 |intervention_ch.png |2022-03-18 15:13:58|
|10|19 |2022-03-23 08-01-45.png|2022-03-23 11:30:28|
+--+-----+------------------------------------------+-------------------+

对不起,如果解释得不好或者我的英语不好.....如果需要我可以给你更多细节

您可以使用 ROW_NUMBER() 来识别每个子组的最新行。那么过滤就简单了。

例如:

select
from (
  select
    edu.id as id, ud.id as docUp, 
    ud.nom_origine as nomUD, ud.creation,
    row_number() over(partition by edu.id order by ud.creation desc) as rn
  from etape_document_uploade as edu
  left join upload_document as ud 
    on edu.id = ud.etape_document_uploade_id and candidature_id = 12
  where etape_id = 2
) x
where rn = 1