mysql 索引相关的操作

🥓主键索引(非重复索引)

主键默认就是索性

创建表的时候可以指定主键,如设置ID为自动递增,

    id   bigint unsigned auto_increment comment 'id'
        primary key,
        ...

🧂unique索引(非重复索引)

除了主键,unique也是索引,只有一个列的表示这列的数据不能重复,多个列的表示不能同时重复。

比如下面的表示bridge_from这列和bridge_to这列不能同时重复。

已经有a,b的情况下,就不能在插入a,b值了,但是可以插入a,c或者c,b这样的值。表示的是同时满足

这个对于数据库查询单条值的特别有用,
如JPA中findByName这样的语句,如果name不是唯一的,就会导致查询失败报错,如果数据库里面限制了唯一性,就不会出现这样的问题。

方式一🍳/建表的时候指定

create table activity_lottery_timing_code (
id bigint(20) not null auto_increment comment '',
`phone` varchar(32) default null comment '手机号',
`member_id` bigint(20) default null comment '会员ID',
`activity_id` bigint(20) default null comment '定时开奖活动ID',
`code` varchar(32) not null comment '10位的抽奖券码',
`branch_id` bigint(20) default '-1',
`created` datetime default current_timestamp comment '记录创建时间',
`updated` datetime default current_timestamp on update current_timestamp comment '记录最后一次更新时间',
`sn` bigint(20) default null comment '操作流水号',
`sts` int(11) default '1' comment '数据状态,0无效1有效',
primary key (`id`),
key `idx_code` (`code`) using btree,
key `idx_activity_id` (`activity_id`) using btree,
key `idx_created` (`created`) using btree,

UNIQUE KEY `activity_id_code` (`activity_id`,`code`)
)comment='券码记录表';

方式二🥙/已有的表追加

alter table activity_lottery_timing_code add unique key `activity_id_code` (`activity_id`,`code`);

删除 unique索引

alter table activity_lottery_timing_code drop index `activity_id_code`;

🍖普通索引(可重复索引)

但是我们最常见的用法是,想要增加索引来加快查询效率。

其实就是非常简单的一条sql语句

create index idx_user_address
    on s_transaction (user_address);

含义就是创建一个索引,
索引名称是idx_user_address(可以自己定)
s_transaction这个表上
索引的字段是user_address

🥨查看索引

当表建的比较久的时候,我们忘记了哪些字段有索引的时候该怎么查看表的索引呢?

show index from s_transaction;

就是查询s_transaction这个表的索引有哪些。
在这里插入图片描述

🍿 删除索引

Q: 有些索引建错了,怎么删除索引?

A : 一般是根据索引名称来删除

比如我们之前查出来的三个索引,我想去掉普通索引,索引名称是idx_user_address,那么这样就能删除掉s_transaction表上面的这个索引了。

drop index idx_user_address on s_transaction;

注意:表数据量很大的时候尽量避免新增和删除索引,会很慢。

索引本质上是对数据进行了排序,百万数据的时候,进行重新排序,可以想象这个效率,
所以千万不要看测试服没问题然后在生产环境测试。那可能就直接挂掉了。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值