简体   繁体   English

如何在同一查询中订购两次

[英]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:您可以尝试通过原始 SQL 表达式进行排序:

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.这将做的是,它将首先根据tags_count descending排序,然后将排序后的结果集按title descending排序。然后取前10结果并返回它们。

This is the query that worked for me.这是对我有用的查询。 Thank you @SebastianPalma for your help!感谢@SebastianPalma 的帮助!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM