優化MYSQL資料庫的方法

2021-06-21 14:50:03 字數 2786 閱讀 2468

1、選取最適用的字段屬性,盡可能減少定義字段長度,盡量把字段設定not null,例如'省份,性別',最好設定為enum

2、使用連線(join)來代替子查詢:

a.刪除沒有任何訂單客戶:delete from customerinfo where customerid notin(select customerid from orderinfo)

b.提取所有沒有訂單客戶:select from customerinfo where customerid notin(select customerid from orderinfo)

c.提高b的速度優化:select from customerinfo left join orderidcustomerinfo.customerid=orderinfo.customerid

where orderinfo.customerid is null

3、使用聯合(union)來代替手動建立的臨時表

a.建立臨時表:select name from `nametest` union selectusername from `nametest2`

4、事務處理:

a.保證資料完整性,例如新增和修改同時,兩者成立則都執行,一者失敗都失敗

mysql_query("begin");

mysql_query("insert intocustomerinfo (name) values ('$name1')";

mysql_query("select * from`orderinfo` where customerid=".$id");

mysql_query("commit");

5、鎖定表,優化事務處理:

a.我們用乙個select 語句取出初始資料,通過一些計算,用update 語句將新值更新到表中。

包含有write 關鍵字的lock table 語句可以保證在unlock tables 命令被執行之前,

不會有其它的訪問來對inventory 進行插入、更新或者刪除的操作

mysql_query("lock tablecustomerinfo read, orderinfo write");

mysql_query("select customeridfrom `customerinfo` where id=".$id);

mysql_query("update `orderinfo`set ordertitle='$title' where customerid=".$id);

mysql_query("unlocktables");

6、使用外來鍵,優化鎖定表

a.把customerinfo裡的customerid對映到orderinfo裡的customerid,

任何一條沒有合法的customerid的記錄不會寫到orderinfo裡

create table customerinfo

(customerid int not null,

primary key(customerid) 

)type = innodb;

create table orderinfo

(orderid int not null,

customerid int not null,

primarykey(customerid,orderid),

foreign key (customerid)references customerinfo

(customerid) on deletecascade  

)type = innodb;

注意:'on delete cascade',該引數保證當customerinfo表中的一條記錄刪除的話同時也會刪除order

表中的該使用者的所有記錄,注意使用外來鍵要定義事務安全型別為innodb;

7、建立索引:

a.格式:

(普通索引)->

建立:create index 《索引名》 on tablename (索引字段)

修改:alter table tablename add index [索引名] (索引字段)

創表指定索引:create table tablename([...],index[索引名](索引字段))

(唯一索引)->

建立:create unique 《索引名》 on tablename (索引字段)

修改:alter table tablename add unique [索引名] (索引字段)

創表指定索引:create table tablename([...],unique[索引名](索引字段))

(主鍵)->

它是唯一索引,一般在建立表是建立,格式為:

creata table tablename([...],primary key[索引字段])

8、優化查詢語句

a.最好在相同字段進行比較操作,在建立好的索引欄位上儘量減少函式操作

例子1:

select * from order whereyear(orderdate)<2008;(慢)

select * from order whereorderdate<"2008-01-01";(快)

例子2:

select * from order whereaddtime/7<24;(慢)

select * from order whereaddtime<24*7;(快)

例子3:

select * from order where title like"%good%";

select * from order wheretitle>="good" and name<"good";

優化MYSQL資料庫的方法

1 資料庫設計方面,這是dba和architect的責任,設計結構良好的資料庫,必要的時候,去正規化 英文是這個 denormalize,中文翻譯成啥我不知道 允許部分資料冗餘,避免join操作,以提高查詢效率 2 系統架構設計方面,表雜湊,把海量資料雜湊到幾個不同的表裡面.快慢表,快表只留最新資料...

優化MYSQL資料庫的方法

1 建立索引 a 普通索引 建立 create index 索引名 on tablename 索引字段 修改 alter table tablename add index 索引名 索引字段 創表指定索引 create table tablename index 索引名 索引字段 b 唯一索引 建立...

優化Mysql資料庫的方法

第 一 優化索引 sql 語句 分析慢查詢 第二 設計表的時候嚴格按照資料庫的設計正規化來設計資料庫 第三 我們可以加上 memcached 快取,將經常被訪問到的資料,但是不需要經常變化的資料放入至 memcached 快取伺服器裡面 第四 還可優化硬體,在硬體層面,我們可以使用更好的一些硬碟 固...