Mysql 一个表中的SQL group by和另一个表中的max
我有三个表Mysql 一个表中的SQL group by和另一个表中的max,mysql,sql,datetime,greatest-n-per-group,window-functions,Mysql,Sql,Datetime,Greatest N Per Group,Window Functions,我有三个表ab,bcd和c。现在我想根据a_idfromabtable进行分组,并从ctable中选择maxdate。这就是我一直尝试的: select ab.a_id, bcd.d_id, c.val, max(c.date) as date from tableab ab, tablebcd bcd, tablec c where ab.b_id = bcd.b_id and bcd.c_id = c.c_id group by ab.a_id 它的工作没有错误,但没有给出正确的结果。我不
ab
,bcd
和c
。现在我想根据a_id
fromab
table进行分组,并从c
table中选择maxdate
。这就是我一直尝试的:
select ab.a_id, bcd.d_id, c.val, max(c.date) as date
from tableab ab, tablebcd bcd, tablec c
where ab.b_id = bcd.b_id
and bcd.c_id = c.c_id
group by ab.a_id
它的工作没有错误,但没有给出正确的结果。我不太懂SQL,所以可能缺少一些简单的东西。谢谢你的帮助 从现有查询开始,直接的方法是
row\u number()
(仅在MySQL 8.0中提供)
row\u number()
通过降序date
对具有相同a\u id
的记录进行排序-然后可以使用此信息筛选表
请注意,我重写了查询以使用标准的显式连接,而不是老式的隐式连接(在
from
子句中使用逗号):此几十年前的语法不应用于新代码。您得到的结果是什么,您期望的结果是什么?文本格式的预期结果示例数据会很有用。@aRvi我希望每个ab.a_id
(最大c.date
)有一行,但我得到多行
select *
from (
select
ab.a_id,
bcd.d_id,
c.val,
row_number() over(partition by ab.a_id order by c.date desc) as rn
from tableab ab
iner join tablebcd bcd on ab.b_id = bcd.b_id
inner join tablec c on bcd.c_id = c.c_id
) t
where rn = 1