【问题标题】:How do you query for records with no associated record (linked via join table)您如何查询没有关联记录的记录(通过连接表链接)
【发布时间】:2022-01-18 00:34:19
【问题描述】:

我有表 A 和表 B,还有一个我们称之为 C 的连接表。

A 到 C 有很多 B。

B 有很多 A 到 C。

C table structure:
a_id
b_id

我正在尝试查找关联 B 为零的 As。

这可以使用连接来完成吗?

目前我正在这样做:

as_with_no_bs = A.select{|a| a.bs.empty?}

但这可能比使用联接效率低得多。

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    假设:

    • c 记录需要 a_id 和 b_id 才能存在
    • 表名是“as”
    • A 与 C 的关系为 has_many :cs
    • C 表名是“cs”

    (一些)可用的解决方案:

    导轨

    # we could use Arel to make this more "code based" but for the sake of example
    A.joins("LEFT OUTER JOIN cs on cs.a_id = as.id")
      .where(cs: {id: nil})
    

    Rails 4 +

    A.where.not(id: C.select(:a_id))
    

    Rails 5+

    A.left_joins(:cs).where(cs: {id: nil})
    

    Rails 6.1+

    A.where.missing(:cs)
    

    【讨论】:

    • 有替代解决方案或上述类似和不同的变体也可以作为基于查询的解决方案有效
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多