My table: ( validfrom
and validto
and 03JUL2014
below all are of type DATE
, not STRING
)
id type validfrom validto
-------------------------------------
1 "APPLE" 10MAY2011 15APR2012
1 "APPLE" 19APR2012 15APR2017
1 "ORANGE" 10MAY2011 15APR2012
1 "ORANGE" 19APR2012 15AUG2018
1 "PEAR" 10MAY2012 15APR2013
1 "PEAR" 10MAY2011 15APR2018
2 "APPLE" 10MAY2011 15APR2017
2 "APPLE" 10MAY2011 15APR2012
2 "ORANGE" 10MAY2011 15APR2012
2 "ORANGE" 10MAY2011 15APR2015
2 "ORANGE" 10MAY2007 15APR2019
2 "PEAR" 10MAY2003 15APR2012
2 "PEAR" 10MAY2006 15APR2022
I want to retrieve all records where id
is 2
and validto
is greater than 03JUL2014
.
Thus I must get:
2 "APPLE" 10MAY2011 15APR2017
2 "ORANGE" 10MAY2007 15APR2019
2 "PEAR" 10MAY2006 15APR2022
I tried:
SELECT type, validfrom, MAX(validto) FROM crew_qualifications
WHERE id=2 AND validto >= 03JUL2014
It only gave me:
2 "PEAR" 10MAY2006 15APR2022
In your query you write MAX(validto) then it return only those row which has validto value is max
you remove MAX(validto) then it return the proper ans
First find the maximum date per type in the given time range. Then join with your table again to get the complete record.
select cq.type, cq.validfrom, cq.validto
from crew_qualifications cq
join
(
select type, max(validto) as validto
from crew_qualifications
where validto >= '2014-07-03'
group by type
) wanted_cq
on wanted_cq.type = cq.type and wanted_cq.validto = cq.validto;
As to your query: You select MAX(validto) without groups, so you get the MAX(validto) for the whole table, ie one record. Along with the MAX(validto) you get a random type and a random validfrom from your table, as you don't specify which type and validfrom you want to see (the minimum, maximum, or the average). (Besides validto >= 03JUL2014
should give you a syntax error. I'm surprised it obviously doesn't. I don't know, how MySQL interprets this here.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.