数据库查询

2018-10-30  本文已影响0人  biubiudog

一、union和union_all

1.union 和 union_all   将两个结果集合并在一起(可以查询不同的表)

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只是将查询出的数据合并显示出来即可

    union则会在运行时查询出结果,再去删除重复的记录,最后返回结果集。

2. 效率上 union all的查询会快很多

3. union查询时查询的列个数,列顺序需要完全一致。


二 、索引

1.在创建数据表时直接创建索引

rails g model user student references

rails创建时会自动的为users表和student_id创建索引:

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. 多对多关系中添加索引

add_index :classroom , [:student_id, :teacher_id]

覆盖索引:create index index_name_and_age on users(name, age)

select name from users where age = 12

单索引查找时,根据条件查找出主键(id),然后通过主键去查找需要搜索的结果。

覆盖索引查找时,直接根据条件查找出对应的结果(name)并返回。

上一篇下一篇

猜你喜欢

热点阅读