mysql基本命令,索引及優化

下載地址: 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 字符並不多。

 

歡迎訪問個人主頁:唐悅瑋的博客

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章