sql语句之外键和索引

drop table if exists class;
create table class(
id int unsigned primary key auto_increment,
name varchar(10)
);

drop table if exists stu;
create table stu(
name varchar(10),
class_id int unsigned
);
-- 外键-------------------------------------------------------------------------------------
-- 扩展1:对于已经存在的表添加外键
-- alter table 从表名 add foreign key(从表字段) references 主表名(主表主键)
alter table stu add foreign key (class_id) references class(id);

-- 扩展2:查看外键和删除外键
show create table stu;

-- CREATE TABLE `stu` (
--   `name` varchar(10) DEFAULT NULL,
--   `class_id` int unsigned DEFAULT NULL,
--   KEY `class_id` (`class_id`),
--   CONSTRAINT `stu_ibfk_1` FOREIGN KEY (`class_id`) REFERENCES `class` (`id`)
-- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3


-- 删除外键
alter table stu drop foreign key stu_ibfk_1;


-- -----------------------------索引----------------------------------------
-- 开启时间检测
set profiling =1;

-- 查询示例数据 num=1000的值
select * from test_index where num =100;
-- 查看运行时间
show profiles;
-- 添加索引
create index num_index on test_index(num);
-- 再次执行查询数据操作
select * from test_index where num =100;
-- 查看运行时间
show profiles;

-- 扩展1:查看索引
show index from test_index;

-- 扩展2:创建表时添加索引
create table create_index(
id int primary key,
name varchar(10) unique, -- unique : 设置端唯一值
age int,
key(age) -- 指定添加索引方法
);
-- 查看索引
show index from create_index;


-- 扩展3 : 删除索引
-- drop index 索引名称 on 表名;
drop index age on create_index;












评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值