简体   繁体   中英

MySql select Mix and Max year

Hi guys I am developing a php and mysql application. 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.

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:

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.

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`

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.

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