mysql基本命令,索引及优化

本文详细介绍了MySQL的基本操作,包括数据库和表的创建、数据的增删改查、索引的使用及优化技巧,帮助读者掌握MySQL数据库的管理和维护。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下载地址: https://www.mysql.com/downloads/

#创建和使用数据库

  • 显示数据库show databases;
  • 创建数据库create database test;
  • 访问数据库mysql> use test;
  • 显示表 show tables;
  • 创建表
     create table `user` (
          `id` int(11) not null auto_increment comment '主键',
          `username` varchar(48) default null comment '用户名',
          `password` varchar(48) default null comment '密码',
          `create_time` timestamp not null default current_timestamp comment '创建时间',
          `update_time` timestamp not null comment '修改时间',
          `state` int not null comment '状态',
          primary key (`id`)
        )engine=innodb default charset=utf8 comment='用户表';
    
  • 查看表结构 describe user;或者desc user;
  • 插入数据
    • 将文本文件加载pet.txt到 pet表中,使用以下语句: load data local infile '/path/user.txt' into table user;
    • 普通脚本插入:
      insert into user values (1,'tyw','123','','',0);
      
  • 更新数据
          update user set username = 'tboss' where id = 1;
    
  • 查询数据
            select * from user;
    

#索引

  • 查看表索引
show index from user;
    or
show keys from user;

  • 创建索引
-- 普通索引
create index index_username on user (username)
-- 全文索引
create fulltext index index_username on user (username)
-- 主键索引
alter table user add primary key (id)
-- 外键索引
alter table user add unique (id)
  • 删除索引
drop index index_username on user

alter table user drop index index_username
-- 删除主键索引
alter table user drop primary key
-- 删除外键索引
alter table user drop unique

索引查询注意

  • like时“%aa%”不会使用索引,而like “aa%”会使用索引
  • where子句中使用了索引的话,order by中的列不会使用索引

#字段操作

  • 添加表字段
    • 添加字段
          alter table user add extend varchar(10);
    
    • 修改字段
          alter table user change extend extend1 varchar(11) not null;
    
  • 删除表字段
          alter table user drop extend1;
    

#优化

  • 表关联查询时务必遵循 小表驱动大表 原则;
  • 使用查询语句 where 条件时,不允许出现 函数,否则索引会失效;
  • 使用单表查询时,相同字段尽量不要用 OR,因为可能导致索引失效,比如:SELECT * FROM table WHERE name = 'zhangsan' OR name = 'lisi',可以使用 UNION 替代;
  • LIKE 语句不允许使用 % 开头,否则索引会失效;
  • 组合索引一定要遵循 从左到右 原则,否则索引会失效;比如:SELECT * FROM table WHERE name = '张三' AND age = 18,那么该组合索引必须是 name,age 形式;
  • 索引不宜过多,根据实际情况决定,尽量不要超过 10 个;
  • 每张表都必须有 主键,达到加快查询效率的目的;
  • 分表,可根据业务字段尾数中的个位或十位或百位(以此类推)做表名达到分表的目的;
  • 分库,可根据业务字段尾数中的个位或十位或百位(以此类推)做库名达到分库的目的;
  • 表分区,类似于硬盘分区,可以将某个时间段的数据放在分区里,加快查询速度,可以配合 分表 + 表分区 结合使用;

警告

在使用 MySQL 或 MariaDB,不要用“utf8”编码,改用“utf8mb4”。这里(https://mathiasbynens.be/notes/mysql-utf8mb4#utf8-to-utf8mb4)提供了一个指南用于将现有数据库的字符编码从“utf8”转成“utf8mb4”。 MySQL 的“utf8mb4”是真正的“UTF-8”。 MySQL 的“utf8”是一种“专属的编码”,它能够编码的 Unicode 字符并不多。

 

欢迎访问个人主页:唐悦玮的博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Tangyuewei

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值