如何查找第二个表中没有的记录,Rails

时间:2014-07-16 02:15:31

标签: mysql ruby-on-rails-3

我有两个表,表A和表B.表A有很多表B表示一对多的关系。我想找到表A中不在表B中的那些记录。我怎样才能找到该记录?

谢谢,提前

4 个答案:

答案 0 :(得分:0)

试试这个

SELECT ta.*
FROM TableA AS ta
    LEFT OUTER JOIN TableB AS tb
        ON ta.id = tb.fk
WHERE tb.fk IS NULL

答案 1 :(得分:0)

您可以使用foreign_key中的table B来执行此操作

让我们假设你的表名为statescountries,关系是country has_many statesstate belongs_to country。所以states表格会有一个{{ 1}}。

在ActiveRecord Way中,请执行以下操作

foriegn_key country_id

如果@country = Country.find(params[:id]) #the record of table A which you want to see if it exists in table B @state = State.where(:country_id => @country.id) 返回@state,则nil中有no such record countries(table A)

答案 2 :(得分:0)

@Slyzz写道:

TabelA.joins("left outer join table_bs on table_as.id = table_bs.table_as_id").where("table_bs.id" => nil)

答案 3 :(得分:0)

供将来参考,您正在使用Rails 5,可以使用新的left_outer_joins方法:

ModelA.where(group_id: group_id)
      .left_outer_joins(:relation_in_model_a)
      .merge(ModelB.where(id: nil))