开发者

mysql order by multiple columns

开发者 https://www.devze.com 2023-03-04 02:45 出处:网络
I have a post table and a reply table. both tables have a created column which record when it is being created. and the post tabl开发者_Python百科e have a last_reply_created and is updated whenever a

I have a post table and a reply table. both tables have a created column which record when it is being created. and the post tabl开发者_Python百科e have a last_reply_created and is updated whenever a reply made to a post with that post id.

first question: in the posts page, I want to display all posts that sorted by whichever last_reply_created or created in post table comes first.

second question: Can you design the post and reply table better regarding this problem?

My workaround is to insert last_reply_created whenever a post is created.


Your last_reply_created should be NULL until there is a reply and the creation time for a reply should always be more recent than the created value. This allows you to use coalesce like this:

select *
from your_table
order by coalesce(last_reply_created, created) desc

And presumably every row has a non-NULL created.

I don't see any problem with caching the last_reply_created value in your post table. If you're going to be using it a lot then it doesn't make much sense to keep computing it over and over again.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号