2014-06-13 56 views
0

我有两个表格方向和注册,我想执行一个加入查询。这里是每个表的模式...Mysql加入导轨

create_table "orientations", :force => true do |t| 
    t.date  "class_date" 
    t.text  "class_time" 
    t.integer "seats" 
    t.boolean "active",  :default => true 
    t.datetime "created_at",     :null => false 
    t.datetime "updated_at",     :null => false 
    end 

create_table "registrations", :force => true do |t| 
    t.integer "orientation_id" 
    t.string "first_name" 
    t.string "last_name" 
    t.string "email" 
    t.string "student_id" 
    t.string "phone" 
    t.string "registration_cancellation_token" 
    t.datetime "registration_cancelled_at" 
    t.boolean "checked_in",      :default => false 
    t.boolean "cancelled",      :default => false 
    t.datetime "created_at",           :null => false 
    t.datetime "updated_at",           :null => false 
    t.text  "program" 
    end 

我在找的是所有的方向在两个日期之间的所有注册。我想出了这个...

Registration.where(Orientation.where created_at: => @[email protected]_date) 

当然,这种语法是假的,但很快它将有助于获得我所期待的。

+0

Registration.includes([:方向]),其中(”。 orientation.created_at在?和?之间,@start_date,@end_date)...试试这个,让我知道 – userRandom

回答

1

使用它来获取所有的方位都注册两个日期之间:

Registration.joins(:orientation).where(orientations: {:class_date => @[email protected]_date}) 

joins执行INNER JOIN它过滤不具有关联的行。

但是,如果你想保留那些没有关联的行,然后去includes,其执行LEFT OUTER JOIN

Registration.includes(:orientation).where(orientations: {:class_date => @[email protected]_date}) 
+0

谢谢Kirti,但是这些都不会返回结果。仅供参考一些注册没有orientation_id's。这会导致查询返回没有结果? – Lumbee

+0

有趣。如果我使用第二个查询(包含),并使用puts在控制台中查看结果,则返回一个空数组。以下是控制台输出:http://pastie.org/9287293。但是,如果我去我的MySQL数据库并执行'选择'方向'。*从'方向'哪里('方向'.'class_date'下'2014-06-01'和'2014年6月7日');''那么它会返回有效的结果。 – Lumbee

+0

@Lumbee使用'nil'的注册orientation_id将不会成为第一个查询结果的一部分,因为它执行INNER JOIN。但第二个查询应该涵盖由于左外连接引起的那些查询。此外,你想'class_date'列或'created_at'列的条件?在你提到'created_at'的问题中,在上面的评论中你使用'class_date'?在mysql –