0

我正在使用 Rails,并且我有一个Link带有此表的 ActiveRecord 模型:

create_table "links", :force => true do |t|
  t.string   "name",        :null => false
  t.integer  "sender_id",   :null => false
  t.integer  "receiver_id", :null => false
end

add_index "links", ["name"], :name => "index_links_on_name"
add_index "links", ["sender_id", "receiver_id"], :name => "index_links_on_sender_id_and_receiver_id", :unique => true

我想做的是选择name = "follow"从源到目的地以及从目的地到源存在的每个链接。

例如,具有以下条目:

id | name     | sender_id | receiver_id
---------------------------------------
66 | "follow" | 1         | 2
67 | "follow" | 2         | 1
68 | "follow" | 1         | 3
69 | "fuu"    | 3         | 1
70 | "bar"    | 2         | 25
71 | "bar"    | 25        | 2

...我只想得到6667ids 结果。因为 sender_id1和 receiver_id67从源链接到目标,也从目标链接到源(在这两种情况下都使用“跟随”名称)。

我们能做到吗,只用一个 SQL 查询(直接在 SQL 或 ActiveRecord ORM 中)?非常感谢!

4

1 回答 1

2

尝试以下查询>>

select * from tablename t1,t2 where t1.sender_id = t2.receiver_id and t2.sender_id=t1.receiver_id and Name like follow"
于 2012-09-21T14:30:41.767 回答