【问题标题】:How to transform query in sql for query in rails如何将sql中的查询转换为rails中的查询
【发布时间】:2021-09-19 07:17:30
【问题描述】:

如何使用左连接转换此查询,并且在 rails 中不存在查询,我使用的是 rails 6.0.3

此查询必须从tableB中收集所有不存在代码且到期日期小于参数传递日期的项目

query_for_delete_codes = "
SELECT expires_at, code FROM tableA
LEFT JOIN tableB ON code = tableB.created_code
WHERE NOT EXISTS(
  SELECT 1 FROM tableB WHERE tableB.created_code = code
)
AND expires_at < '#{date_limit}'
"

【问题讨论】:

  • 你能用find_by_sql吗?

标签: mysql sql ruby-on-rails activerecord


【解决方案1】:

我不知道你的模型名称,所以我将模型命名为 tableA A 和 tableB B。也许这样的东西对你有用:

class A < ApplicationRecord
  has_many :bs, foreign_key: :created_code, primary_key: 'code'
end

class B < ApplicationRecord
  belongs_to :a, foreign_key: :code, primary_key: 'created_code'
end

A.select(:expires_at, :code)
  .left_joins(:bs)
  .where.not(bs: { created_code: code })
  .where('expires_at < ?', date_limit)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多