我正在尝试获取表格中的行。
想象一下,我有两条记录(t1 和 t2)。我想获得在 t2.start_hour 和 t2.finish_hour 之间没有 t1.start_hour 的行。我基本上只想得到几个小时内与另一个没有冲突的事件。
这是表格:
create_table "occurrences", :force => true do |t|
t.string "start_hour"
t.string "finish_hour"
t.date "start_date"
t.date "finish_date"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "activity_id"
end
这是我到目前为止提出的 SQL 查询:
Occurrence.find_by_sql("SELECT * FROM occurrences t1 INNER JOIN occurrences t2 ON (t1.start_hour NOT BETWEEN t2.start_hour and t2.finish_hour)")
它给了我重复的结果。我无法删除它们并获得正确答案。
我在这里先向您的帮助表示感谢。
例子
输入
#<Occurrence id: 1, start_hour: "19:00", finish_hour: "20:20", start_date: "2012-05-30", finish_date: "2012-05-30", created_at: "2012-05-30 09:58:19", updated_at: "2012-05-30 09:58:19", activity_id: 1>,
#<Occurrence id: 2, start_hour: "19:30", finish_hour: "20:10", start_date: "2012-05-30", finish_date: "2012-05-30", created_at: "2012-05-30 09:58:19", updated_at: "2012-05-30 09:58:19", activity_id: 2>,
#<Occurrence id: 3, start_hour: "22:00", finish_hour: "23:20", start_date: "2012-05-30", finish_date: "2012-05-30", created_at: "2012-05-30 09:58:20", updated_at: "2012-05-30 09:58:20", activity_id: 3>
输出
#<Occurrence id: 1, start_hour: "19:00", finish_hour: "20:20", start_date: "2012-05-30", finish_date: "2012-05-30", created_at: "2012-05-30 09:58:19", updated_at: "2012-05-30 09:58:19", activity_id: 1>,
#<Occurrence id: 3, start_hour: "22:00", finish_hour: "23:20", start_date: "2012-05-30", finish_date: "2012-05-30", created_at: "2012-05-30 09:58:20", updated_at: "2012-05-30 09:58:20", activity_id: 3>
start_hour = 19:30 的记录不输出,因为在另一个记录的 19:00 和 20:20 之间。
编辑:
我得到了解决方案:
Occurrence.find_by_sql("SELECT start_hour FROM occurrences WHERE start_hour NOT IN (SELECT t2.start_hour FROM occurrences t1 INNER JOIN occurrences t2 ON ((t1.activity_id <> t2.activity_id AND t2.start_hour BETWEEN t1.start_hour and t1.finish_hour)))")
谢谢您的帮助