如何使用Squeel / ActiveRecord表示此SQL子查询?

时间:2013-09-04 22:27:14

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 squeel

我今天有点大脑褪色,无法弄清楚我应该如何使用ActiveRecord / Squeel / ARel正确表达这个SQL查询:

SELECT `d1`.* FROM `domain_names` d1
WHERE `d1`.`created_at` = (
  SELECT MAX(`d2`.`created_at`)
  FROM `domain_names` d2
  WHERE `d2`.`owner_type` = `d1`.`owner_type`
  AND `d2`.`owner_id` = `d1`.`owner_id`
  AND `d2`.`key` = `d1`.`key`
)

有什么想法吗?

背景:DomainName模型具有多态所有者以及“密钥”字段,允许所有者拥有许多不同类型的域名。上面的查询为每个唯一的[owner_type, owner_id, key]元组提取最新的域名。

修改

这是使用JOIN的相同查询:

SELECT `d1`.* FROM `domain_names` d1
JOIN (
  SELECT `owner_type`, `owner_id`, `key`, MAX(`created_at`) max_created_at
  FROM `domain_names`
  GROUP BY `owner_type`, `owner_id`, `key`
) d2
  ON `d2`.`owner_type` = `d1`.`owner_type`
    AND `d2`.`owner_id` = `d1`.`owner_id`
    AND `d2`.`key` = `d1`.`key`
WHERE `d1`.`created_at` = `d2`.`max_created_at`

0 个答案:

没有答案