[英]How to select all records greater than a date in mysql table?
My table: ( validfrom
and validto
and 03JUL2014
below all are of type DATE
, not STRING
) 我的表格:(以下的 validfrom
和validto
以及03JUL2014
均为DATE
类型,而不是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
. 我想检索id
为2
且validto
大于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 在您的查询中,您写入MAX(validto),然后仅返回有效值为max的那些行
you remove MAX(validto) then it return the proper ans 您删除MAX(validto),然后返回正确的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. 关于您的查询:您选择不带组的MAX(validto),以便获得整个表(即一条记录)的MAX(validto)。 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). 除了未指定要查看的类型和有效值(最小值,最大值或平均值)之外,还从表中获得了MAX(validto)随机类型和有效validfrom。 (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.) (除了validto >= 03JUL2014
应该会给您一个语法错误。我很惊讶它显然没有。我不知道,MySQL在这里是如何解释的。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.