简体   繁体   中英

How to order twice in the same query

How do you order something twice in the same query? For example I can order search for the top ten tagged courses by

categories = Category.all.limit(10).order(tags_count: :desc)

I can also order them alphabetically by

categories = Category.all.order(title: :desc)

How do you order by title after the top ten tagged courses have been queried? I tried this but it didn't work

categories = Category.all.limit(10).order(tags_count: :desc).order(title: :desc)

You may try ordering by a raw SQL expression:

categories = Category.all.limit(10).order('tags_count desc, title desc')

You can try like this -

Category.order(tags_count: :desc, title: :desc).limit(10)

What this will do is that it will first sort based on the tags_count in descending order and then sort the sorted result set on title in descending order.Then take the first 10 results and return those.

This is the query that worked for me. Thank you @SebastianPalma for your help!

Category.where(id: Category.order(tags_count: :desc).limit(10)).order(title: :desc)

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