据我所知,ActiveRecord 中的“where”方法在使用属性哈希创建 sql 命令时不授予条件顺序。例如:
Student.where(:classroom_id => 1, :serial_no => 10, :name => 'Allen')
# SELECT `students`.* FROM `students` WHERE `students`.`name` = 'Allen' AND `subscriptions`.`serial_no` = 10 AND `subscriptions`.`classroom_id` = 1
我们可以使用带有数组的“where”来强制条件格式,如下所示:
Student.where(["classroom_id = ? AND serial_no = ? AND name = ?", 1, 10, 'Allen'])
# SELECT `students`.* FROM `students` WHERE (classroom_id = 1 AND serial_no = 10 AND name = 'Allen')
但是我们会失去使用属性哈希的灵活性。实际上,我们只想按顺序强制执行前两个条件(即,classic_id 和 serial_no)。
有没有办法强制按顺序排列前两个条件并使用给定的哈希分配以下条件?
更新:
为什么我关心条件的顺序?
因为我对(classroom_id,serial_no)使用了多列索引。如果我们使用以下两个查询,则索引有效:
SELECT * FROM students WHERE classroom_id = 1 AND serial_no = 10 AND name = 'Allen'
SELECT * FROM students WHERE classroom_id = 1 AND name = 'Allen'
但不适用于(或未充分利用)这两个:
SELECT * FROM students WHERE name = 'Allen' AND classroom_id = 1 AND serial_no = 10
SELECT * FROM students WHERE serial_no = 10 AND classroom_id = 1 AND name = 'Allen'