新手问题 不改数据库字段的情况下,自定义排序输出

cconev · 2012年08月30日 · 最后由 hexawing 回复于 2013年11月05日 · 3609 次阅读

我在做一个 Slider 功能: ' ids = Configs.postids.split("|").collect { |id| id.to_i }' '@posts = Post.where(:_id.in => ids).limit(5)'

设置 postids 为: '4|2|1|3|7'

怎样保证最后数据显示还是按照 4|2|1|3|7 的顺序呢?

1 楼 已删除

用 mysql 的话,可以用 field:

Post.where(...).order("field(id, #{ids})")

.order("field(post.id, #{ids.join(',')})")

#4 楼 @cconev 刚看了下 mongo mappermongoid sort 貌似都没有这个功能

那就取出来再在内存中排序吧

要是循环传 ID 给 Cell 渲染,是会多次查询数据库很影响性能么?

#2 楼 @quakewang 这个办法貌似不适用于有 null 的…… 我想把 null 排最前,其余的倒序, 找了很久也没找到方法……

啊,终于找到了,备忘一下……

select
  products.*
from
  products inner join priorities
  on products.category = priorities.category
order by
  priorities.priority is null, -- this to put null values at the end, or use 'is not null' to put null at first
  priorities.priority,
  products.id                  -- or some other field

或者在 rails 里

.where(true).order("personal_messages.read_at is not null").order("personal_messages.id DESC")
#未读消息(阅读时间为null)在最前,其余以id倒序
需要 登录 后方可回复, 如果你还没有账号请 注册新账号