选择以下2列mysql上的最大值

时间:2016-11-11 09:09:27

标签: mysql sql performance

我有一张像

这样的表格
date(int), time(int), code(int), title(varchar)

我应该选择特定代码的最后一行,然后选择最长日期中最长时间的行。表非常大,我应该在查询中使用更少的资源

date     time code title
20161110 1045 5522 plant1
20161110 1045 5522 plant1
20161110 1100 5522 plant1
20161111 1030 5522 plant1
20161111 1045 5522 plant1

我希望获得一行

20161111 1045 5522 plant1

那是我糟糕的sql

select * 
from ep_ft_consumptions_experimental as cons 
    (inner join (select max(date) as md 
                 from ep_ft_consumptions_experimental 
                 where plant_code=5522 
                   and d1=1
                ) dr 
        on cons.date = dr.md) 
    (inner join (select max(time) as mt 
                 from ep_ft_consumptions_experimental
                ) tr 
        on cons.time = tr.time

1 个答案:

答案 0 :(得分:1)

这很简单。使用ORDER BYLIMIT 1

select cons.* 
from ep_ft_consumptions_experimental as cons 
where cons.code = 5522
order by cons.date desc, cons.time desc
limit 1 ;

至于效率,如果你还没有,你只需要在(code, date, time)上添加一个综合索引。