0

假设我有两个模型,submission has_many submissionstate

并且 tablesubmissionstates具有以下列:

id | submission_id | state_id | created_at

查询是

SELECT submission_id, state_id
FROM submissionstates ss
JOIN (
  SELECT MAX(created_at) as created_at
  FROM submissionstates ss
  GROUP BY submission_id
) x
ON ss.created_at = x.created_at
WHERE state_id = 0
4

1 回答 1

1

就像 Saurabh 提供的链接一样,您最终将 sql 片段放入 rails 查询方法;像这样的东西

list = SubmissionState.select("submission_id, state_id")
  .where(:state_id => 0)
  .joins("
    JOIN (
      SELECT MAX(created_at) as created_at
      FROM submissionstates ss
      GROUP BY submission_id
    ) x
    ON ss.created_at = x.created_at
  ")

puts list.length

老实说,此时您最好使用 find_by_sql

sql = "
  SELECT submission_id, state_id
  FROM submissionstates ss
  JOIN (
    SELECT MAX(created_at) as created_at
    FROM submissionstates ss
    GROUP BY submission_id
  ) x
  ON ss.created_at = x.created_at
  WHERE state_id = ?
  AND some_other_value = ?
"

list = SubmissionState.find_by_sql([sql, 0, 'something-else'])
puts list.length

注意:一旦你开始使用连接或 find_by_sql rails 就像它给你对象一样,但实际上它们将包含在 select 子句中定义的任何属性,并且 find_by_sql 将所有属性作为字符串返回,这可能很烦人

于 2013-03-06T15:54:25.143 回答