所以,我有一个图片模式,可以在 full_size 下载和 presentation_size 。当用户下载的照片我跟踪这个照片的 full_downloads 和 presentation_downloads 属性。
So, I have a Photo model which can be downloaded at full_size and presentation_size. When a user downloads a photo I track this on the photo's full_downloads and presentation_downloads attribute.
这一切都很好。
有时候我想知道有多少总下载量已经出现了。我有一个简单的方法, total_downloads 它看起来像这样:
Sometimes I want to know how many total downloads there have been. I have a simple method, total_downloads which looks like so:
def total_downloads self.full_downloads + self.presentation_downloads end我的问题是:我希望能够通过这三个(全,presentation,总下载量)的订购照片。前两个是容易的,但你如何通过两列的和做的命令?请注意,这需要在两个的SQLite和PG最低兼容。
My question is: I would like to be able to order photos by all three of these (full, presentation, total downloads). The first two are easy, but how do you do an order by the sum of two columns? Note this needs to be both SQLite and PG compatible at minimum.
A面的问题,会是更快,使 total_downloads 的查询方法,如果有什么写的,最好的方法是什么?我所知道的总结上,你可以调用 Photo.sum(...)的类,但我不知道该怎么做了两列上的一个记录。
A side question, would it be faster to make the total_downloads method a query, and if so what's the best way to write that? I know to sum on the class you can call Photo.sum(...), but I'm not sure how to do that for two columns on a single record.
谢谢!
推荐答案您可以试试这个:
Photo.order('full_downloads + presentation_downloads')
这将运行该SQL查询:
It will run this SQL query:
SELECT "photos".* FROM "photos" ORDER BY full_downloads + presentation_downloads这可能是缓慢的,但。如果你有一个大的数据集,并使用这种排序顺序的时候,你应该考虑创建一个 total_downloads 列,并重新计算其价值,如果记录的 full_downloads 或 presentation_downloads 列的变化。
This is potentially slow though. If you have a large dataset and use this sort order often, you should consider creating a total_downloads column and recalculating its value if the record's full_downloads or presentation_downloads column changes.
更多推荐
扶手:排序按两列的总和
发布评论