3

我的代码是这个

user_friends =Friend.find(:all, :select => "friend_id", :conditions => "app_user_id =12345")

second_user_friends = Friend.find(:all, :select => "friend_id", :conditions => "app_user_id = 123321")

common_friends_id = user_friends.map{|uf| uf.friend_id}.to_a & second_user_friends.map{|suf| suf.friend_id}.to_a

common_friends = Friend.find(:all, :conditions => "friend_id in (#{common_friends_id.join(",")}) 
  and app_user_id = 12345")

这需要很多时间我能以某种方式做吗请帮助我

4

2 回答 2

1

尝试

 ActiveRecord::Base.connection.select_all("SELECT f1.* FROM friends f1 
         JOIN friends p2 ON f2.friend_id = f1.friend_id 
         WHERE f1.app_user_id = 12345 and f2.app_user_id = 123321")

对于 Rails 2

Friend.all(:joins=>"JOIN friends f2 ON f2.friend_id = friends.friend_id",
       :conditions =>"friends.app_user_id = 12345 and f2.app_user_id = 123321")

对于 Rails 3

Friend.where("friends.app_user_id = 12345 and f2.app_user_id = 123321")
      .joins("JOIN friends f2 ON f2.friend_id = friends.friend_id")
于 2013-05-09T08:19:38.253 回答
0

我认为这应该足够了。

second_user_friend_ids = Friend.find(:all, :select => "friend_id", :conditions => "app_user_id = 123321").map(&:id)

common_friends = Friend.find(:all, :conditions => "friend_id in (#{second_user_friend_ids.join(",")}) and app_user_id = 12345")
于 2013-05-09T08:14:40.513 回答