【发布时间】:2017-09-02 23:50:37
【问题描述】:
谁能帮我弄清楚如何在 Rails 中编写以下 SQL 语句?
SELECT * FROM shifts a
INNER JOIN (
SELECT shifts.date, shifts.time, max(shifts.barber_id) as 'barber_id'
FROM shifts
WHERE shifts.date = '2017-09-06' and shifts.is_free = true
GROUP BY shifts.date, shifts.time
) b
ON a.date = b.date AND a.time = b.time AND a.barber_id = b.barber_id
WHERE a.`is_free` = true AND a.date = '2017-09-06'
因为子查询和主查询中的 where-conditional 相同,所以我使用的范围如下:
scope :available, -> { where('shifts.is_free', true).where('shifts.date', '2017-09-06').order(date: :desc, time: :asc) }
我还创建了子查询的范围:
scope :grouped_shifts, -> { select("date, time, max(barber_id) as barber_id").group(:date, :time).available }
但我不知道如何链接范围以加入方法。我可以将它作为参数传递吗?像这样:
scope :something, -> { joins(self.grouped_shifts).available }
或者在这种情况下我不应该使用作用域? 提前感谢您的帮助!
【问题讨论】:
-
通过查看您的 SQL,我看不出整个查询的结果与仅内部查询的结果有何不同。
-
在我的表中,我有几条相同日期和时间的记录,但 barber_id 字段不同。我要做的是过滤表格并在每组日期和时间中只选择 barber_id 最大值的行,因此在该组中将只有一个唯一记录
标签: mysql ruby-on-rails rails-activerecord