一、union和union_all
1.union 和 union_all? ?將兩個結(jié)果集合并在一起(可以查詢不同的表)
eg:?
select max(id) from users where created_at <= "#{Time.now.strftime('%F %T')}" union all? select max(id) from users where created_at <= "#{(Time.now - 1.month).strftime('%F %T')}"
注意:
1. union all只是將查詢出的數(shù)據(jù)合并顯示出來即可
????union則會在運行時查詢出結(jié)果,再去刪除重復(fù)的記錄,最后返回結(jié)果集。
2. 效率上 union all的查詢會快很多
3. union查詢時查詢的列個數(shù),列順序需要完全一致。
二 、索引
1.在創(chuàng)建數(shù)據(jù)表時直接創(chuàng)建索引
rails g model user student references
rails創(chuàng)建時會自動的為users表和student_id創(chuàng)建索引:
add_index :users, :student_id
2.手動添加索引
rails g migration add_student_id_index_to_users?
修改change部分,手動添加索引
def change
? ? add_index :users, :student_id
end
3. 多對多關(guān)系中添加索引
add_index :classroom , [:student_id, :teacher_id]
覆蓋索引:create index index_name_and_age on users(name, age)
select name from users where age = 12
單索引查找時,根據(jù)條件查找出主鍵(id),然后通過主鍵去查找需要搜索的結(jié)果。
覆蓋索引查找時,直接根據(jù)條件查找出對應(yīng)的結(jié)果(name)并返回。