관리 메뉴

투덜이 개발자

MySQL 날짜 SORT(order by) 가 안될 경우 본문

DataBase/MySQL

MySQL 날짜 SORT(order by) 가 안될 경우

엠투 2023. 5. 31. 10:16
반응형

MySQL 날짜 SORT(order by) 가 안될 경우

select 
		h_seq
		, history_date
		, DATE_FORMAT(history_date,'%Y') as history_year
		, DATE_FORMAT(history_date,'%m.%d') as history_date
		, contents
from tbl_history
where view_yn = 'Y' and del_yn = 'N'
order by history_date desc, h_seq desc

h_seq|history_date|history_year|history_date|contents                                |
-----+------------+------------+------------+----------------------------------------+
    2|  2022-12-18|2022        |12.18       |탈북민 건강검진 지원                             |
    3|  2022-08-17|2022        |08.17       |해외의료진 임상연수 1차 (카자흐스탄 4명, 몽골 2명)         |
    4|  2022-08-12|2022        |08.12       |카자흐스탄 고려인 장학생 장학 사업 (5명)                |
    5|  2022-08-04|2022        |08.04       |하계의료봉사 (딸띄고르간, 우슈토베) 08.04 ~ 08.14      |
    6|  2022-07-03|2022        |07.03       |(사)작은빛 창립총회                             |
    7|  2022-07-01|2022        |07.01       |해밀학교(다문화) 학생 건강검진 지원                    |
    8|  2022-03-30|2022        |03.30       |우크라이나 긴급 구호물품 전달 (의료용품 500Set + 마스크 1만장)|
    1|  2023-02-08|2023        |02.08       |해외의료진 임상연수 2차 (카자흐스탄 4명, 몽골 4명)         |

위와 같이 정렬이 안될때가 있다.

그럴경우 UNIX_TIMESTAMP 를 사용하면 된다.

select 
		h_seq
		, history_date
		, DATE_FORMAT(history_date,'%Y') as history_year
		, DATE_FORMAT(history_date,'%m.%d') as history_date
		, contents
from tbl_history
where view_yn = 'Y' and del_yn = 'N'
order by UNIX_TIMESTAMP(history_date) desc, h_seq desc

h_seq|history_date|history_year|history_date|contents                                |
-----+------------+------------+------------+----------------------------------------+
    1|  2023-02-08|2023        |02.08       |해외의료진 임상연수 2차 (카자흐스탄 4명, 몽골 4명)         |
    2|  2022-12-18|2022        |12.18       |탈북민 건강검진 지원                             |
    3|  2022-08-17|2022        |08.17       |해외의료진 임상연수 1차 (카자흐스탄 4명, 몽골 2명)         |
    4|  2022-08-12|2022        |08.12       |카자흐스탄 고려인 장학생 장학 사업 (5명)                |
    5|  2022-08-04|2022        |08.04       |하계의료봉사 (딸띄고르간, 우슈토베) 08.04 ~ 08.14      |
    6|  2022-07-03|2022        |07.03       |(사)작은빛 창립총회                             |
    7|  2022-07-01|2022        |07.01       |해밀학교(다문화) 학생 건강검진 지원                    |
    8|  2022-03-30|2022        |03.30       |우크라이나 긴급 구호물품 전달 (의료용품 500Set + 마스크 1만장)|

제대로 정렬이 되었다.

반응형