0

我正在尝试获取表格中的行。

想象一下,我有两条记录(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)))")

谢谢您的帮助

4

2 回答 2

0

未经测试(从内存中),您需要排除记录本身-> t1.activity_id <> t2.activity_id left join 否则您将无法获得没有右侧的好记录

需要对此进行测试:p

SELECT * FROM occurrences t1 
left JOIN occurrences t2 
ON (t1.activity_id <> t2.activity_id and t1.start_hour BETWEEN t2.start_hour and t2.finish_hour)
where t2.activity_id is null
于 2012-05-30T10:13:28.597 回答
0

假设表中有3条记录。(我用整数代替数据时间,因为这会更容易)

  id     start    end
   1      1        3
   2      4        5
   3      7        9

当我试图找到开始不在开始和结束之间的行时,比对于 id =1 第一行都为真并且会出现结果。同样,对于 id =2 (start=4) 的行,两行都符合条件(使第三行出现两次结果)第三行也会发生同样的情况,你最终会得到六行。

它不是很清楚您要在这里实现什么,但是放置 distinct 将删除重复项。

编辑:您可能会考虑将内部连接放在开始和结束日期。

于 2012-05-30T10:01:06.430 回答