【问题标题】:ActiveRecord OUTER JOINActiveRecord 外连接
【发布时间】:2015-01-19 15:43:16
【问题描述】:

在 Google 群组中,我添加了我的问题 - here infact

我的问题是如何用“Rails 方式”来表达这个外连接:

SELECT 
`employees`.`id` AS t0_r0, `employees`.`name` AS t0_r1, `employees`.`last_seen` AS t0_r2, `employees`.`created_at` AS t0_r3, `employees`.`updated_at` AS t0_r4, `employees`.`punch_clock_id` AS t0_r5, `employees`.`account_id` AS t0_r6, `employees`.`born_at` AS t0_r7, `entrances`.`id` AS t1_r0, `entrances`.`employee_id` AS t1_r1, `entrances`.`clocked_at` AS t1_r2, `entrances`.`created_at` AS t1_r3, `entrances`.`updated_at` AS t1_r4, `entrances`.`entrance_type` AS t1_r5 
FROM 
    `employees` 
LEFT OUTER JOIN 
    `entrances` ON `entrances`.`employee_id` = `employees`.`id` AND (`entrances`.`clocked_at` BETWEEN '2015-01-01' AND '2015-01-31’) 
WHERE 
    `employees`.`account_id` = 2 

我的第一反应是:

current_user.account.employees.includes(:entrances).where( 'entrances.clocked_at' => @month_range)

但这确实只为员工提供了入口(除非我松开声明的“位置”部分,在这种情况下我会得到所有员工(以及所有 25 万个入口!!!))

【问题讨论】:

  • 感谢 @xlembouras 编辑我的问题,以便以正确的方式呈现 SELECT 语句!尽我所能,但编辑不允许我用正确的重音“排除”声明 - 就像帮助指示我的那样:(

标签: ruby-on-rails activerecord outer-join arel


【解决方案1】:

如果您想包含 employees 而没有 entrances,则必须通过调用 entrances.id IS NULL 在您的 where 语句中明确包含该情况。

current_user.account.employees.includes(:entrances).where( 'entrances.id IS NULL OR entrances.clocked_at = ?', @month_range)

根据@month_range 包含的内容,最后一部分可能看起来略有不同。

【讨论】:

  • 抱歉没有回复:(但你的建议没有通过,恐怕ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'entrances.id' in 'where clause': SELECT employees.* FROM employees` WHERE employees.account_id = 2 AND (entrances.id IS NULL OR entrys.clocked_at = '2015-02-18')`
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-16
  • 2020-07-01
  • 2015-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多