Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 966
Luke Snowden Avatar asked Jun 24 '26 20:06

Luke Snowden


1 Answers

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;
like image 196
Saharsh Shah Avatar answered Jun 28 '26 06:06

Saharsh Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!