首页 > 解决方案 > 返回行中的mysql Max(日期)值

问题描述

我查询时在 mytable 中

SELECT * FROM mytable WHERE adsh='0000002178-18-000009' and tag='assets'

我得到这个结果

adsh tag ddate value
0000002178-18-000009 Assets 2016-12-31 246872000.00
0000002178-18-000009 Assets 2017-12-31 282704000.00

但我希望只返回包含 max(ddate) 的行,即 2017-12-31 行注意还有许多其他不同的标签。但是由于该表包含 >100k 行,因此我希望确保在将其扩展到所有行之前进行正确的查询。

我尝试了许多不同的查询和变体,但没有雪茄:/

SELECT *,max(ddate) FROM mytable WHERE adsh='0000002178-18-000009' and tag='Assets'

返回错误的行

SELECT * FROM mytable
WHERE ddate = (select max(ddate) and adsh='0000002178-18-000009' and tag='Assets' from mytable)

返回 0 行

SELECT * FROM mytable
WHERE ddate = (select max(ddate) and adsh='0000002178-18-000009' and tag='Assets' from mytable)

返回 0 行

SELECT DISTINCT adsh,tag,ddate,value from mytable
WHERE ddate = (select max(ddate) from mytable) group by adsh 

但这也不是我所期望的

有谁知道我怎么能做到这一点?

太感谢了 :)

标签: mysqlsqldatetimemaxgreatest-n-per-group

解决方案


你似乎想要:

select * 
from mytable
where ddate = (
    select max(ddate) 
    from mytable
    where adsh='0000002178-18-000009' and tag='Assets' 
)

where通过重复外部查询子句中的条件,您将获得更准确的信息:

select * 
from mytable
where adsh = '0000002178-18-000009' and tag = 'Assets'  and ddate = (
    select max(ddate) 
    from mytable
    where adsh = '0000002178-18-000009' and tag = 'Assets' 
)

以防万一,让我指出,如果您确定没有顶级关系,这可以更简单地完成limit

select * 
from mytable
where adsh = '0000002178-18-000009' and tag = 'Assets'
order by dddate desc limit 1

最后:如果你运行的是 MySQL 8.0,你也可以使用窗口函数:

select *
from (
    select t.*,
        rank() over(order by ddate desc) as rn
    from mytable t
    where adsh = '0000002178-18-000009' and tag = 'Assets'
) t
where rn = 1

推荐阅读