Schema與資料型別優化

2021-10-16 10:08:15 字數 2490 閱讀 8363

關於整數型別:

1.整數型別都有可選的unsigned,表示不允許負值。

2.為整數型別指定顯示寬度是沒有意義的,只會控制客戶端顯示字元的個數。

關於實數型別:

1.不精確型別:float,double; 精確型別:decimal

2.cpu不支援對decimal進行直接運算,可以直接對浮點進行運算;同時,decimal會占用更多的空間,mysql將數字打包

儲存到乙個二進位制字串中,每4個位元組儲存9個數字。

3.可以使用bigint代替decimal,放大對應倍數即可。

char型別的優點:

1.定長的資料

2.很短的資料,因為varchar還需要1 or 2個位元組記錄字串的長度;比如說y或者n

3.經常更新的列可以用char,因為varchar會產生碎片

日期和時間型別:

1.datetime可以表示到2023年,使用8個位元組。

2.timestamp只能表示到2023年,使用4個位元組,且與時區有關,推薦使用timestamp。

3.timestamp的行為規則比較複雜,建議使用show create table檢視。

計數器表:

1.考慮到高併發問題的計數器表:(round函式的使用,可以刪除)

create

table hit_counter(

slot tinyint

unsigned

notnull

primary

key,

cnt int

unsigned

notnull

)engine

=innodb

;--需要預先在表裡插入100行資料

update hit_counter set cnt = cnt +

1where slot=

round

(rand()*

100)

;--統計結果

select

sum(cnt)

from hit_counter;

2.每隔一段時間需要開始乙個新的計數器,同時不能預先生成行。

create

table daily_hit_counter(

daydate

notnull

, slot tinyint

unsigned

notnull

, cnt int

unsigned

notnull

,primary

key(

day, slot)

)engine

=innodb

;--使用on duplicate key

insert

into daily_hit_counter(

day,slot,cnt)

values

(current_date

,round

(rand()*

100),1

)onduplicate

keyupdate cnt=cnt+1;

3.如果上述round進行約束,那麼計數器表中會產生大量的行;所以需要乙個週期任務合併所有的結果到0號槽位。

update daily_hit_counter as c

inner

join

(select

day,

sum(cnt)

as cnt,

min(slot)

as mslot

from daily_hit_counter

group

byday

)as x using

(day

)set c.cnt =

if(c.slot=x.mslot, x.cnt,0)

, c.slot =

if(c.slot=x.mslot,

0, c.slot)

;--然後刪除其餘的槽位

delete

from daily_hit_counter where slot <>

0and cnt=

0;

alter table問題:

1.mysql中大部分修改表的操作都是,建立乙個空表,然後從舊表中查出所有資料插入新錶。

2.如果要修改表的預設值,可以使用alter table column,這個語句會直接修改.frm檔案而不涉及資料。

3.alter table允許使用alter column,modify column,和change column語句修改列,這三種操作不同

Schema與資料型別優化

關於資料型別選擇的一些記錄 tinyint 8 smallint 16 mediumint 24 int 32 bigint 64 可選屬性 unsigned。mysql可以為整型指定寬度,如int 11 但大多數時候沒有意義,只是規定了一些互動工具用來顯示字元的個數。從mysql4.1開始,每個字...

Schema與資料型別優化

選擇優化的資料型別 1.更小的通常更好 一般情況下,應該盡量使用可以正確儲存資料的最小資料型別。因為它們占用更少的磁碟。記憶體和cpu快取,並且處理時需要的cpu週期也更少 2.簡單就好 簡單資料型別的操作通常需要更少的cpu週期 3.盡量避免null 通常情況下最好指定列為not null。通常把...

Schema與資料型別優化

schema 是資料庫物件的集合 比如使用者建立了表,索引,檢視,儲存過程等物件,那麼這些物件就構成了schema 應根據系統將要執行的查詢語句來設計schema,往往需要權衡各種因素。反正規化的設計可以加快某些型別的查詢 同時可能使另一些型別的查詢變慢 新增計數表和彙總表可以優化查詢 這些表的維護...