Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4154356
  • 博文数量: 240
  • 博客积分: 11504
  • 博客等级: 上将
  • 技术积分: 4277
  • 用 户 组: 普通用户
  • 注册时间: 2006-12-28 14:24
文章分类

全部博文(240)

分类: Mysql/postgreSQL

2014-03-03 13:09:45

对于关系型数据库而言,针对表的检索,一般来说,建立合适的索引就可以达到很好的检索效果。(这里不包含表设计的合理与否)
比如像状态列这样可选择性非常低的值,该如何检索?  其实这个已经不是关系型数据库擅长的方面了。 但是如果出于历史或者许多不可抗拒的原因,
我们还得在关系表中进行优化,该咋办?   一般来说,就是建立静态表。 但是静态表也是多重多样,该如何选择? 我下面列举几个简单的例子,当然了,
由于个人的脑子尺度不够大,有可能有些遗漏。


原始表。
20 完条记录, 大概36MB大小。

点击(此处)折叠或打开

  1. t_girl>create table rank_status (id integer not null, i_status varchar(3) not null);




第一种呢,就是建立LIST 表,这种表,可以当做静态表,也可以当做原始表来做相关的更新。
只有2条记录,大概720KB大小。

点击(此处)折叠或打开

  1. t_girl>create table rank_status_extend (i_status varchar(3) not null, ids text);




我们可以对两张表都做对应的更新操作。



点击(此处)折叠或打开

  1. 插入一条记录。
  2. t_girl> insert into rank_status values (222222,'yes');
  3. Time: 4.397 ms
  4. t_girl>update rank_status_extend set ids = ids ||','||'222222' where i_status = 'yes';
  5. Time: 43.725 ms


  6. 删除一条记录。
  7. t_girl>delete from rank_status where i_status = 'yes' and id = 1;
  8. Time: 47.339 ms
  9. t_girl>update rank_status_extend set ids = replace(ids,',1,',',') where i_status = 'yes';
  10. Time: 45.046 ms


  11. 更新一条记录。
  12. t_girl>update rank_status set id = 1000 where i_status = 'yes' and id = 20;
  13. Time: 65.834 ms
  14. t_girl>update rank_status_extend set ids = replace(ids,',20,',',1000,') where i_status = 'yes';
  15. Time: 85.974 ms




我们看到,在对表的写操作中,第二张表会比第一张慢一点。


其实我们最主要的是关心读操作。其实在读上面还是很有优势的。



点击(此处)折叠或打开

  1. t_girl>select count(*) as total from rank_status where i_status = 'yes';
  2.  total
  3. -------
  4.  99600
  5. (1 row)


  6. Time: 86.563 ms


  7. t_girl>select length(ids) - length(replace(ids,',','')) + 1 as total from rank_status_extend where i_status = 'yes';
  8.  total
  9. -------
  10.  99600
  11. (1 row)


  12. Time: 35.762 ms


  13. t_girl>select string_agg(id::text,','),i_status from rank_status group by i_status;
  14. Time: 113.393 ms
  15. t_girl>select ids from rank_status_extend where i_status = 'yes';
  16. Time: 2.447 ms






接下来第二种呢,就是分别建立两张表, 但是这两张表呢,少了存放状态值的字段,所以在尺寸上小了很多。

点击(此处)折叠或打开

  1. t_girl>create table rank_status_yes (id int not null);
  2.  3552 kB
  3. t_girl>create table rank_status_no(id int not null);
  4.  3584 kB



当然这张表的检索肯定比原始表来的快,这里,我就不演示了。


第三种呢,就是建立一张物化视图,

点击(此处)折叠或打开

  1. t_girl>create materialized view mv_rank_status_yes as select * from rank_status where i_status = 'yes';


这种其实和第二种表很类似。只不过不同的是第二种表的维护需要人工来做,而这个视图系统可以维护。
阅读(4845) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~