我有两个表,表A和表B.表A有很多表B表示一对多的关系。我想找到表A中不在表B中的那些记录。我怎样才能找到该记录?
谢谢,提前
答案 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
来执行此操作
让我们假设你的表名为states
和countries
,关系是country has_many states
和state 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))