MySql之索引和主键

MySql之索引和主键

为啥把主键单独放出来:是因为长时间只写select语句,导致对表结构都失去了基础的了解,会对主键和索引的概念有疑问,其实主键是索引的一种,也是一种唯一索引,要求每一个主键的值都是唯一的

索引创建的条件:被频繁作为查询条件的列才应该被定义为索引,也就是where后经常出现的列名

索引越多越好?:小的时候考试一旦有这种越怎么样越怎么样的选项,老师告诉我们千万不要选,为啥呢,我们在更新表的时候还得更新索引,同样会损失效率

索引>唯一索引>主键

在这里插入图片描述

索引的创建

拿来一张平时练手的表的创建语句,在最后有一段create index,就是在创建索引,语法:

create index 索引名字(UK即为unique key,独一无二的) on 表名(列名)
on m_user (username)

create table m_user
(
    id         bigint       not null
        primary key,
    username   varchar(64)  null,
    avatar     varchar(255) null,
    email      varchar(64)  null,
    password   varchar(64)  null,
    status     int(5)       not null,
    created    datetime     null,
    last_login datetime     null
);

create index UK_USERNAME
    on m_user (username);

索引的删除

drop index UK_USERNAME on m_user;

唯一索引的创建

只不过是在索引的创建语句中新增一个unique

create unique index UK_USERNAME on m_user(username);

唯一索引的删除

和删除索引是一样的

drop index UK_USERNAME on m_user;

主键的创建

一个表只能有一个主键,而且这个主键是不可以为空值的

再拿来一张平时使用的数据库表的建表语句,最后一句的alter语句即为创建主键,语法:

alert table 表名 add primary key(列名)

create table tai1_cases
(
    id               int auto_increment,
    group_id         int                    not null,
    sort_id          int                    null,
    case_name        char(128)              not null,
    yn               int     default 1      not null,
    constraint tai1_cases_id_uindex
        unique (id)
);

create index tai1_cases_group_id_index
    on tai1_cases (group_id);

alter table tai1_cases
    add primary key (id);

主键的删除

alter table tai1_cases drop primary key ;
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值