一个复杂的SQL语句

时间:2010-12-15 20:15:24

标签: mysql sql ruby-on-rails

我有两张桌子。

  

表A - >帖子(id,title,user_id,...,created_at,..)

  

tableB - >重新发布(id,post_id,user_id,... created_at,...)

所以,在我的rails app控制器中:

@posts = Post.find(:all, :conditions => ["user_id = ? OR id IN ( select post_id from reposts where user_id=? )", '1', '1'], :limit => 9)

它工作正常,但是:

我需要通过两个列“created_at”(表POSTS的created_at和表REPOSTS的created_at)的一个组合对我的@posts进行排序

任何帮助?

1 个答案:

答案 0 :(得分:1)

试试这个:

class Post
  has_many :reposts
end


class Repost
  belongs_to :post
end    

Post.all(
  :include => :reposts, 
  :conditions => ["posts.user_id = ? OR reposts.user_id = ?", 1, 1],
  :order => "posts.created_at DESC, reposts.created_at DESC
)