上一節(jié)是使用存儲(chǔ)函數(shù)分別向兩張表插入1000條數(shù)據(jù)岂昭,使用時(shí)間基本差不多守问,由于數(shù)據(jù)量較小羡榴,所以InnoDB與MyISAM的差別不是很明顯碧查,所以現(xiàn)在我們跟別向兩張表插入1000000條數(shù)據(jù),得出的結(jié)果是:
MyISAM引擎執(zhí)行時(shí)間---58.848s校仑,每秒大約插入16993條
InnoDB引擎執(zhí)行時(shí)間---4078.217s忠售,大約用了67分鐘
注:理論上沒這么慢,應(yīng)該與硬件有關(guān)迄沫,所以寫入才這么慢
由此稻扬,可以再次證明:MyISAM引擎在執(zhí)行寫入的時(shí)候速度要遠(yuǎn)比InnoDB快,但是像存儲(chǔ)用戶信息的這類表羊瘩,有可能在網(wǎng)站中會(huì)參與事務(wù)泰佳,所以一般會(huì)選擇在數(shù)據(jù)庫中混合使用存儲(chǔ)引擎。需要參與事務(wù)的表使用InnoDB困后,像用戶表乐纸,只是參與讀寫比如需要管理員在后臺(tái)向表中寫入數(shù)據(jù),這種的可以使用MyISAM摇予,因此汽绢,當(dāng)我們在建立數(shù)據(jù)表的時(shí)候,可以多方面選擇侧戴,挑選適合應(yīng)用場景的存儲(chǔ)引擎宁昭。
InnoDB與MyISAM查詢性能對比:
select count(*) from user_sys;
InnoDB查詢時(shí)間:0.194s
select count(*) from user_sys2;
MyISAM查詢時(shí)間:0.001s
查詢性能優(yōu)化
以user_sys表為例跌宛,存儲(chǔ)引擎默認(rèn)為InnoDB,查詢user_name為user34的用戶,sql語句為
select * from user_sys where user_name='user34';
不添加索引的情況下积仗,查詢時(shí)間為0.427s
為user_name添加索引疆拘,索引類型為Normal(普通索引),索引方法為BTREE寂曹,查詢時(shí)間為0.001s
場景:注冊時(shí)用戶名不能重復(fù)哎迄,實(shí)現(xiàn)方法:
select count(*) from user_sys where user_name = username;
如果查詢出對應(yīng)的用戶名大于0,則不能注冊此用戶名隆圆,同時(shí)可能還需要鎖表禁止用戶操作漱挚,這樣的話性能不是太好,所以可以為user_name建立一個(gè)唯一索引渺氧,當(dāng)用戶注冊的時(shí)候旨涝,執(zhí)行sql語句:
insert into user_sys (user_name,user_pwd) values('user34',123123');
如果user34用戶名存在,則sql語句執(zhí)行失敗侣背,不會(huì)向表中插入數(shù)據(jù)
登錄日志表###
判斷用戶名和密碼是否匹配白华,如果匹配則返回該行數(shù)據(jù),如果不匹配則返回一個(gè)錯(cuò)誤行贩耐。
無論登錄成功與否弧腥,都記錄一次日志
小技巧:
在查詢用戶名或密碼時(shí),通常的sql語句是這樣的:
select * from user_sys where user_name='user234';
可以加入limit潮太,以提高查詢速度
select * from user_sys where user_name='user234' limit 1;
用戶登錄:寫一個(gè)存儲(chǔ)過程鸟赫,匹配用戶名和密碼
存儲(chǔ)過程名稱及參數(shù):select_user_login(IN _user_name varchar(20),IN _user_pwd varchar(20));
begin
set @gid=0;
set @user_name='';
set @_result='login_success';
select id,user_name into @gid,@user_name from user_sys where user_name=_user_name and user_pwd=_user_pwd limit 1;
if @gid=0 then #登錄失敗
set @_result='login_error';
end if;
insert into user_log(user_id,log_type) values(@gid,@_result); #日志統(tǒng)計(jì)
select * from (select @_result as _result) a,(select @gid,@user_name) b;
end
查詢:call select_user_login('user23','123');
無論有沒有此用戶,都會(huì)返回一行結(jié)果消别,只要判斷第一行即可。
后臺(tái)如果有個(gè)功能台谢,有一個(gè)列表通過一個(gè)頁面查看當(dāng)前系統(tǒng)的用戶操作日志寻狂。要求顯示
1)用戶id
2)用戶名
3)日志時(shí)間
最基本的sql就是,關(guān)聯(lián)兩張表:
select a.user_name,a.id,b.log_date from user_sys a,user_log b where a.id=b.user_id order by b.id desc limit 0,100000;
另一種方法就是加入冗余字段user_name:
select a.* from user_log a order by id desc limit 0,100000;
執(zhí)行時(shí)間:
第一種:0.183s
第二種:0.158s
執(zhí)行時(shí)間第二種加入冗余字段要快一些