I searched everywhere but I couldn’t get a answer that satisfy my questions. I want to order MySQL results by published date.
I will explain exactly what I want to do.
All posts are saving to database with following fields
Post_id = auto increment
post_title = varchar
posted_date = datetime (gmdate('Y-m-d H:i:s') )
post_status = int
post_published_date = datetime (gmdate('Y-m-d H:i:s') )
After saving the posts I want display posts order by post_published date. When posts are inserted post_published_date will be NULL and when change the post_status to 1 and post_published_date date will be added.
So I’m ordering posts as below
SELECT * FROM posts WHERE post_status = 1 ORDER BY post_published_date DESC, Post_id DESC
Also tried below
SELECT * FROM posts WHERE post_status = 1 ORDER BY STR_TO_DATE(post_published_date, '%Y-%m-%d %H:%i:%s')
DESC, Post_id DESC
All above works well. My question is which is the best approach from above or is there a better way to do this (performance wise). Appreciate your time.
Edit: Also i would like to know whether i need to use STR_TO_DATE
for a MySQL datetime column.
Only you can use below query will be best:
SELECT * FROM posts WHERE post_status = 1 ORDER BY post_published_date DESC
SELECT * FROM posts WHERE post_status = 1
ORDER BY STR_TO_DATE(post_published_date, '%Y-%m-%d %H:%i:%s')
DESC, Post_id DESC
Try this query. just removed the semicolon after STR_TO_DATE
function. Are you using Wordpress?
best approach is ORDER BY post_published_date DESC
because its simply descending all posts for poststatus =1
Code :
SELECT * FROM posts WHERE post_status = 1 ORDER BY post_published_date DESC, Post_id DESC