简体   繁体   English

MySQL选择混合和最大年份

[英]MySql select Mix and Max year

Hi guys I am developing a php and mysql application. 嗨,大家好,我正在开发一个php和mysql应用程序。 I want to select Min and Max from year. 我想从年份中选择“最小值”和“最大值”。 It should show correct year like below: 它应该显示正确的年份,如下所示:

Min = 1998
Max = 2014

My table structure like below 我的表结构如下

Table: Students 表:学生

year varchar(32)    utf8_unicode_ci 
-------------------------------
06-04-2012
02-05-2014
19-04-1999
05-05-2014
06-04-1998

I try to use MySql Min and Max but not working well. 我尝试使用MySql Min和Max,但效果不佳。

SELECT MIN(`year`) AS Year FROM `Students`

SELECT Max(`year`) AS Year FROM `Students`

Please help me with this issue. 请帮我解决这个问题。

You should not store dates as strings. 您不应该将日期存储为字符串。 You should store them as dates. 您应该将它们存储为日期。

But, because you have this format, you can use the right() function to get the year: 但是,由于具有这种格式,因此可以使用right()函数获取年份:

select min(right(year, 4)), max(right(year, 4))
from students;

If, for some unfathomable reason, you do have to store dates as strings, then use the ISO standard YYYY-MM-DD format. 如果由于某种不可思议的原因而必须将日期存储为字符串,请使用ISO标准YYYY-MM-DD格式。

If you want the minimum of the entire values as a date, then convert it to a date: 如果要将整个值中的最小值作为日期,则将其转换为日期:

select min(str_to_date(year, '%d-%m-%Y')), max(str_to_date(year, '%d-%m-%Y'))
from students;

But, you should be storing the date using the proper data type in the first place. 但是,首先应该使用正确的数据类型存储日期。

使用YEAR()函数就像

SELECT MIN(YEAR(`year`)) AS Year FROM `Students`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM