Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 获取组中每个成员最近编辑的行_Mysql_Sql - Fatal编程技术网

Mysql 获取组中每个成员最近编辑的行

Mysql 获取组中每个成员最近编辑的行,mysql,sql,Mysql,Sql,我敢肯定,这个问题以前肯定被问过很多次,也回答过很多次,但我找不到一个与我的情况相匹配的解决方案来修改它以使其生效。我想我必须休息一天,因为我想检索的数据应该很简单,而且我相信我以前在其他项目上也做过类似的工作 我有两个表,数据有点像下面的 t1_id title 1 This is the first one 2 This is another one 及 我希望从查询中返回的数据如下所示 t1_id title t2_id edi

我敢肯定,这个问题以前肯定被问过很多次,也回答过很多次,但我找不到一个与我的情况相匹配的解决方案来修改它以使其生效。我想我必须休息一天,因为我想检索的数据应该很简单,而且我相信我以前在其他项目上也做过类似的工作

我有两个表,数据有点像下面的

t1_id  title
    1  This is the first one
    2  This is another one

我希望从查询中返回的数据如下所示

t1_id  title                  t2_id  edit_date   content
    1  This is the first one      3  02/02/2020  Some edited text
    2  This is another one        2  01/02/2020  Some other text
因此,我需要每个
t1\u id
一行,它应该是第二个表中最新的
edit\u date

我主要处理几个嵌套的子查询,但它依赖于日期列上的联接,我不喜欢这个联接,我有一个子查询选择
max(edited_date)
,并在
t2_t1_id
上分组,然后联接到自身以选择剩余数据,然后将其联接到第一个表上,所以这是一个有点混乱的解决方案,这个问题感觉应该有一个更好的解决方案


这似乎是一种经常做的事情,因此有了一个简单、优雅的解决方案?

您可以使用
row\u number()
join

select t1.*, t2.*
from table1 t1 left join
     (select t2.*,
             row_number() over (partition by t2_t1_id order by edit_date desc) as seqnum
      from table2 t2
     ) t2
     on t2.t2_t1_id = t1.t1_id and t2.seqnum = 1;
使用
行编号()


…这就是为什么它是这个标签下最常被问到的问题
select t1.*, t2.*
from table1 t1 left join
     (select t2.*,
             row_number() over (partition by t2_t1_id order by edit_date desc) as seqnum
      from table2 t2
     ) t2
     on t2.t2_t1_id = t1.t1_id and t2.seqnum = 1;
select * from
(
select t1_id, title,t2_id, edit_date, content, 
     row_number() over(partition by t1_id order by edit_date desc) as rn
from table1 t inner join table2 t1 on t.t1_id=t1.t2_t1_id
)A where rn=1