Home > Database > Mysql Tutorial > body text

[原创]状态值在数据库中的检索

WBOY
Release: 2016-06-07 17:36:41
Original
1238 people have browsed it

对于关系型数据库而言,针对表的检索,一般来说,建立合适的索引就可以达到很好的检索效果。(这里不包含表设计的合理与否)比如像状态列这样可选择性非常低的值

对于关系型数据库而言,针对表的检索,一般来说,建立合适的索引就可以达到很好的检索效果。(这里不包含表设计的合理与否)

比如像状态列这样可选择性非常低的值,该如何检索?  其实这个已经不是关系型数据库擅长的方面了。 但是如果出于历史或者许多不可抗拒的原因,

我们还得在关系表中进行优化,该咋办?   一般来说,就是建立静态表。 但是静态表也是多重多样,该如何选择? 我下面列举几个简单的例子,当然了,

由于个人的脑子尺度不够大,有可能有些遗漏。


原始表。

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

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


第一种呢,就是建立LIST 表,这种表,可以当做静态表,也可以当做原始表来做相关的更新。

只有2条记录,大概720KB大小。

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


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


插入一条记录。

t_girl> insert into rank_status values (222222,'yes'); Time: 4.397 ms t_girl>update rank_status_extend set ids = ids ||','||'222222' where i_status = 'yes'; Time: 43.725 ms

删除一条记录。

t_girl>delete from rank_status where i_status = 'yes' and id = 1; Time: 47.339 ms t_girl>update rank_status_extend set ids = replace(ids,',1,',',') where i_status = 'yes'; Time: 45.046 ms


更新一条记录。

t_girl>update rank_status set id = 1000 where i_status = 'yes' and id = 20; Time: 65.834 ms t_girl>update rank_status_extend set ids = replace(ids,',20,',',1000,') where i_status = 'yes'; Time: 85.974 ms


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


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


t_girl>select count(*) as total from rank_status where i_status = 'yes'; total ------- 99600 (1 row) Time: 86.563 ms t_girl>select length(ids) - length(replace(ids,',','')) + 1 as total from rank_status_extend where i_status = 'yes'; total ------- 99600 (1 row) Time: 35.762 ms t_girl>select string_agg(id::text,','),i_status from rank_status group by i_status; Time: 113.393 ms t_girl>select ids from rank_status_extend where i_status = 'yes'; Time: 2.447 ms



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

t_girl>create table rank_status_yes (id int not null); 3552 kB t_girl>create table rank_status_no(id int not null); 3584 kB

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


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

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

这种其实和第二种表很类似。只不过不同的是第二种表的维护需要人工来做,而这个视图系统可以维护。


本文出自 “上帝,咱们不见不散!” 博客,请务必保留此出处

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!