Sql 获取同一表中的行
我在试着在一张桌子上找行 想象一下我有两条记录t1和t2。我想得到在t2.start\u小时和t2.finish\u小时之间没有t1.start\u小时的行。我基本上只想在几个小时内得到与另一个事件没有冲突的事件 这是表格:Sql 获取同一表中的行,sql,ruby-on-rails-3,Sql,Ruby On Rails 3,我在试着在一张桌子上找行 想象一下我有两条记录t1和t2。我想得到在t2.start\u小时和t2.finish\u小时之间没有t1.start\u小时的行。我基本上只想在几个小时内得到与另一个事件没有冲突的事件 这是表格: create_table "occurrences", :force => true do |t| t.string "start_hour" t.string "finish_hour" t.date "start_date"
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: 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)))")
感谢您的帮助假设表中有3条记录。我用整数代替数据时间,因为这会更容易
id start end
1 1 3
2 4 5
3 7 9
当我尝试查找行WARS start不在start和end之间时,如果id=1,则第一行都将为true,并将出现结果。类似地,对于id=2 start=4的行,两行都将符合条件,使第三行出现两次结果,第三行也会出现相同的情况,最后将出现六行
现在还不太清楚您在这里想要实现什么,但是放置distinct将删除重复项
<>编辑:您可以考虑在开始和完成日期时加入内部连接。 未从内存中测试。
您需要排除记录本身->t1.activity\u id t2.activity\u id
左键加入,否则你就得不到好的
没有右边的地方
需要测试这个: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
请发布一些示例数据和预期输出。我无法理解您在这里试图实现的目标。如果您能提供更多关于您试图通过此解决的实际问题的详细信息,那就更好了。结果是两条记录的所有字段都为零。编辑:操作系统记录的数量是正确的。
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