第2部分 資料庫SQL語言
資料庫表及索引的建立
資料表(或稱表),是資料庫最重要的組成部分之一。資料庫只是一個架構,資料表才是其實質的內容。舉個例子來說,資料庫就像是一座空曠的房子,而資料表是裡面的傢具,沒有傢具的房子只是一個空殼而已。根據資訊的分類情況,一個資料庫中可能包含若干個不同用途的資料表。
表結構有簡單、有複雜,這就對開發人員提出了要求。如何設計一個表的欄位才是最好的?表的欄位如何命名?如何定義表欄位的類型?如何建立索引?等等。
1. 修改之前的建表指令碼
在作者從事過的某項目中,有一個建表指令碼(基於Sybase資料庫)範例如下:
-- XXX
create table tb_XXX
(
AAA varchar(30) not null, -- AAA
BBB int not null, -- BBB
. . . . . .
. . . . . .
processtime1 varchar(24) default('') null, -- yyyy.mm.dd hh24:mi:ss
processtime2 varchar(24) default('') null, -- yyyy.mm.dd hh24:mi:ss
processtime3 varchar(24) default('') null, -- yyyy.mm.dd hh24:mi:ss
. . . . . .
nextprocesstime varchar(24) default('') not null, -- yyyy.mm.dd hh24:mi:ss
. . . . . .
)
go
create unique index idx1_tb_XXX on tb_XXX(AAA)
create index idx2_tb_XXX on tb_XXX(BBB)
go
可以看出,以上的建表指令碼至少存在以下問題:
(1) 欄位命名不是很恰當。如紅色字型所示的processtime1、processtime2、processtime3,在看完之後,還不知道它們到底是什麼意思。因此,對於欄位的命名,要做到直觀易懂,不要讓別人去猜。
(2) 時間欄位的預設值為空白。如紅色字型所示的nextprocesstime欄位,其預設值為空白。一般而言,對於資料庫建表指令碼中的時間欄位,如無特殊用途,其預設值最好設定為目前時間。
(3) 建立的索引數目過少,且在時間欄位上面未建立索引。在表中很多個欄位,而只建立了兩個索引,個數偏少,可考慮增加索引數目。此外,表中有多個時間欄位,但未在其上面建立索引,要求只要在表中出現了時間欄位,都要考慮在其上建立索引。
2. 修改之後的建表指令碼
修改之後的指令碼範例如下:
-- XXX
create table tb_XXX
(
AAA varchar(30) not null, -- AAA
BBB int not null, -- BBB
. . . . . .
. . . . . .
firstprocesstime varchar(24) default('') null, -- yyyy.mm.dd hh24:mi:ss
secondprocesstime varchar(24) default('') null, -- yyyy.mm.dd hh24:mi:ss
thirdprocesstime varchar(24) default('') null, -- yyyy.mm.dd hh24:mi:ss
. . . . . .
nextprocesstime varchar(24) default convert(varchar,getdate(),102)+' '+convert(varchar,getdate(),108) not null, -- yyyy.mm.dd hh24:mi:ss
. . . . . .
)
go
create unique index idx1_tb_XXX on tb_XXX(AAA)
create index idx2_tb_XXX on tb_XXX(BBB)
create index idx4_tb_XXX on tb_XXX(nextprocesstime)
go
修改的地方如紅色字型所示。與之前的指令碼相比,修改了nextprocesstime欄位的預設值,將索引數目增加到3個,在時間欄位上建立了索引。此外,根據一般的經驗,大表索引個數不超過5個,索引最大欄位數不超過4個。
3. 總結
表是資料庫中最重要的資料結構之一,在建立表的過程中,一定要遵循命名規範、資訊準確、索引恰當等原則。
(本人微博:http://weibo.com/zhouzxi?topnav=1&wvr=5,號:245924426,歡迎關注!)