-- 构建一个简单视图 createview vw_score as (select id,math_score from score);
select*from vw_score; update vw_score set math_score =99where id =2;
多表视图
1 2 3 4 5 6 7
-- 复杂视图(两张表关联) createview vw_student_score as (select stu.id as id ,stu.name as name ,score.math_score from student stu,score score where stu.id = score.student_id);
select*from vw_student_score;
update vw_student_score set math_score =999where id =2;
-- 测试索引效果 createtable tb_index( id bigserial primary key, name varchar(64), phone varchar(64)[] );
-- 添加300W条数据测试效果 do $$ declare i int :=0; begin while i <3000000 loop i = i +1; insertinto tb_index (name,phone) values (md5(random()::text ||current_timestamp::text)::uuid,array[random()::varchar(64),random()::varchar(64)]); end loop; end; $$ language plpgsql;
在没有索引的情况下,先基于name做等值查询,看时间,同时看执行计划
1 2 3 4 5 6
-- c0064192-1836-b019-c649-b368c2be31ca select*from tb_index where id =2222222; select*from tb_index where name ='c0064192-1836-b019-c649-b368c2be31ca'; explain select*from tb_index where name ='c0064192-1836-b019-c649-b368c2be31ca'; -- Seq Scan 这个代表全表扫描 -- 时间大致0.3秒左右
在有索引的情况下,再基于name做等值查询,看时间,同时看执行计划
1 2 3 4 5 6 7
-- name字段构建索引(默认就是b-tree) create index index_tb_index_name on tb_index(name); -- 测试效果 select*from tb_index where name ='c0064192-1836-b019-c649-b368c2be31ca'; explain select*from tb_index where name ='c0064192-1836-b019-c649-b368c2be31ca'; -- Index Scan 使用索引 -- 0.1s左右
测试GIN索引效果:
在没有索引的情况下,基于phone字段做包含查询
1 2 3 4 5
-- phone:{0.6925242730781953,0.8569644964711074} select*from tb_index where phone @>array['0.6925242730781953'::varchar(64)]; explain select*from tb_index where phone @>array['0.6925242730781953'::varchar(64)]; -- Seq Scan 全表扫描 -- 0.5s左右
给phone字段构建GIN索引,在查询
1 2 3 4 5 6 7
-- 给phone字符串数组类型字段构建一个GIN索引 create index index_tb_index_phone_gin on tb_index using gin(phone); -- 查询 select*from tb_index where phone @>array['0.6925242730781953'::varchar(64)]; explain select*from tb_index where phone @>array['0.6925242730781953'::varchar(64)]; -- Bitmap Index 位图扫描 -- 0.1s以内完成