简体   繁体   中英

MySQL - order by string date

I have a meta value which is being joined onto my posts which is the date. I want to be able to only get future posts but this date is a varchar and is in the format of

dd-mm-yyyy

This is what I've tried so far but doesn't seem to work properly

select `posts`.*, `storage_varchars`.`meta_value`

from `posts` left join `storage_varchars` on 
       `posts`.`id` = `storage_varchars`.`post_id` 
where `parent_id` = 20 and 
         DATE(storage_varchars.meta_value) >= NOW() 
order by DATE(storage_varchars.meta_value) asc

Use STR_TO_DATE() function:

Try this:

SELECT p.*, s.meta_value
FROM posts p 
LEFT JOIN storage_varchars s ON p.id = s.post_id 
WHERE parent_id = 20 AND STR_TO_DATE(s.meta_value, '%d-%m-%Y') >= CURRENT_DATE() 
ORDER BY STR_TO_DATE(s.meta_value, '%d-%m-%Y') ASC;

try this

select `posts`.*, `storage_varchars`.`meta_value`

from `posts` left join `storage_varchars` on 
       `posts`.`id` = `storage_varchars`.`post_id` 
where `parent_id` = 20 and 
         STR_TO_DATE(storage_varchars.meta_value, '%d %M %Y') >= NOW() 
order by STR_TO_DATE(storage_varchars.meta_value, '%d %M %Y') DESC

STR_TO_DATE

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