Search code examples
mysqlsqlqsqlquery

Find the row with today's valid price depending on a validFrom date in mySQL


Here it comes. I have the following data:

type, validfrom, price
1, 2018-01-15, 10 
1, 2018-01-20, 20 
1, 2018-01-25, 30 
2, 2018-01-01, 12 
3, 2018-01-01, 18

Today, it's 2018-01-21, I need a query which produces the following result:

1, 2018-01-20, 20
2, 2018-01-01, 12
3, 2018-01-01, 18

I tried different combinations using sub-selects and group-bys but I wasn't able to find a nice, short query solving this problem (and that's working as well).

Any ideas?


Solution

  • In MySQL, you can do:

    select t.*
    from t
    where t.validfrom = (select max(t2.validfrom)
                         from t t2
                         where t2.type = t.type and
                               t2.validfrom < now()
                        );
    

    With an index on t(type, validfrom), this should have very good performance.