美文网首页
web级mysql学习笔记(二)用户登录一:唯一索引的妙用

web级mysql学习笔记(二)用户登录一:唯一索引的妙用

作者: akon2016 | 来源:发表于2017-02-13 02:54 被阅读56次

    上一节是使用存储函数分别向两张表插入1000条数据,使用时间基本差不多,由于数据量较小,所以InnoDB与MyISAM的差别不是很明显,所以现在我们跟别向两张表插入1000000条数据,得出的结果是:
    MyISAM引擎执行时间---58.848s,每秒大约插入16993条
    InnoDB引擎执行时间---4078.217s,大约用了67分钟
    注:理论上没这么慢,应该与硬件有关,所以写入才这么慢
      由此,可以再次证明:MyISAM引擎在执行写入的时候速度要远比InnoDB快,但是像存储用户信息的这类表,有可能在网站中会参与事务,所以一般会选择在数据库中混合使用存储引擎。需要参与事务的表使用InnoDB,像用户表,只是参与读写比如需要管理员在后台向表中写入数据,这种的可以使用MyISAM,因此,当我们在建立数据表的时候,可以多方面选择,挑选适合应用场景的存储引擎。
    InnoDB与MyISAM查询性能对比:

    select count(*) from user_sys;
    InnoDB查询时间:0.194s
    select count(*) from user_sys2;
    MyISAM查询时间:0.001s
    

    查询性能优化
    以user_sys表为例,存储引擎默认为InnoDB,查询user_name为user34的用户,sql语句为

    select * from user_sys where user_name='user34';
    

    不添加索引的情况下,查询时间为0.427s
    为user_name添加索引,索引类型为Normal(普通索引),索引方法为BTREE,查询时间为0.001s

    场景:注册时用户名不能重复,实现方法:

    select count(*) from user_sys where user_name = username;
    

    如果查询出对应的用户名大于0,则不能注册此用户名,同时可能还需要锁表禁止用户操作,这样的话性能不是太好,所以可以为user_name建立一个唯一索引,当用户注册的时候,执行sql语句:

    insert into user_sys (user_name,user_pwd) values('user34',123123');
    

    如果user34用户名存在,则sql语句执行失败,不会向表中插入数据

    登录日志表###

    判断用户名和密码是否匹配,如果匹配则返回该行数据,如果不匹配则返回一个错误行。
    无论登录成功与否,都记录一次日志

    小技巧:
    在查询用户名或密码时,通常的sql语句是这样的:

    select * from user_sys where user_name='user234';
    

    可以加入limit,以提高查询速度

    select * from user_sys where user_name='user234' limit 1;
    

    用户登录:写一个存储过程,匹配用户名和密码
    存储过程名称及参数: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);   #日志统计
        select * from (select @_result as _result) a,(select @gid,@user_name) b;
    end
    

    查询:call select_user_login('user23','123');
    无论有没有此用户,都会返回一行结果,只要判断第一行即可。

    后台如果有个功能,有一个列表通过一个页面查看当前系统的用户操作日志。要求显示
    1)用户id
    2)用户名
    3)日志时间
    最基本的sql就是,关联两张表:

    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;
    

    执行时间:
    第一种:0.183s
    第二种:0.158s
    执行时间第二种加入冗余字段要快一些

    相关文章

      网友评论

          本文标题:web级mysql学习笔记(二)用户登录一:唯一索引的妙用

          本文链接:https://www.haomeiwen.com/subject/pzeaittx.html