一对一双向关系查询

时间:2012-09-21 14:25:16

标签: sql activerecord

我正在使用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

我想要做的是选择从源到目的地以及从目的地到源的每个链接WHERE 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

...我希望得到6667 ID。因为sender_id 1和receiver_id 67从源到目的地以及从目标到源(在两种情况下都带有“跟随”名称)链接。

我们可以只使用一个SQL查询(在SQL中直接使用或ActiveRecord ORM)吗?非常感谢!

1 个答案:

答案 0 :(得分:2)

尝试以下查询>>

select * from tablename t1,t2 where t1.sender_id = t2.receiver_id and t2.sender_id=t1.receiver_id and Name like follow"