我在mysql中有一个连接查询
SELECT c.*, r.*
FROM court c
LEFT JOIN reservations r
ON c.`id` = r.`court_id`
AND `start_time` < '2016-01-20 11:30:00'
AND `end_time` > '2016-01-20 11:00:00'
WHERE `start_time` IS NULL;
供参考:
reservations.rb
belongs_to court
fields: start_time,end_time, court_id
courts.rb
has_many reservations
fields: id, name
我试图将其转换为rails,但似乎无法做到。
我试过Courts.join(:reservations).on("start_time<'2016-01-20 11:00:00'")
但这不起作用
答案 0 :(得分:-1)
转换后的版本将是:
Courts.joins('LEFT JOIN reservations ON courts.id = reservations.id')
.where('reservations.start_time < ? AND reservations.end_time > ?', '2016-01-20 11:30:00', '2016-01-20 11:00:00')
.where(courts: {start_time: nil})
请注意,joins
默认为INNER JOIN
,因此我们需要明确指出LEFT JOIN