【问题标题】:Active record queries - chaining活动记录查询 - 链接
【发布时间】:2015-05-08 08:26:50
【问题描述】:

我正在尝试将以下查询转换为更好的查询,例如使用参数。

我是 Active Record 和 Rails 的新手,所以还在学习。但 null 部分让我失望。因为这需要同时在 mysql 和 sql server 上工作。

contacts = contacts.where("key_contact = true and (c_contact is null or c_contact = false)")

我不应该 key_contact 和 c_contact 位于名为 main_contacts 的不同表中。 联系人表has_manymain_contacts

有人帮忙吗?

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    我会说:

    contacts = contacts.where(key_contact: true).where(c_contact: [nil, false])
    

    在控制台检查结果查询附加.explain

    应该相当于:

    contacts = contacts.where(key_contact: true).where.not(c_contact: true)
    

    无论如何,您应该保持数据库的一致性。所以对于布尔值,有一个默认值来防止null


    根据您的评论:

    contacts = contacts.joins(:main_contacts).where(main_contacts: { key_contact: true }).where.not(main_contacts: { c_contact: true })
    

    【讨论】:

    • 如果空值是可能的,我想我更喜欢 "where(c_contact: [false, nil])"
    • 我应该提到 key_contact 和 c_contact 是不同表中的列,它们位于名为 main_contacts 的表中。如何在上面的查询中指定这一点,因为它正在使用联系人表而不是找到列
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 1970-01-01
    • 2016-03-10
    • 2013-02-01
    • 2013-04-23
    • 2016-11-10
    • 1970-01-01
    相关资源
    最近更新 更多