MySQL 键值的使用

键值的种类:普通索引(index)、唯一索引(unique)、主键(primary key)、外键(foreign key)、全文索引(fulltext)。

一 . 普通索引的使用

  1. 普通索引介绍

    用来给字段值排队,加快对数据库查询的速度,配置后占用物理存储空间;主要类型有:Btree 、B+tree 、hash。

  2. 使用规则

    一个表可以有多个index字段,设置为index的字段的值允许重复,且可以赋NULL值;通常将作为查询条件的字段设置为index字段,index字段的标志是MUL。

  3. 创建索引的方式

    建表时创建索引:
    
    				create table testdb.test(
    											id			int(6),
    											name		char(10),
    											group		char(10),
    											sex			enum(girl,boy),
    											index(id),	index(name)
    											);
    
    在已有的表中创建索引:
    
    					create index index_name on testdb.test(id);
    		
    					index_name:索引名称 	
    
  4. 查看索引信息

    show index from testdb.test \G;				//    \G按行显示
    drop index 字段名 on testdb.test;			//		删除索引
    

二 . 主键及复合主键的使用

  1. 使用规则

    在一个表中只能创建一次主键(primary key)字段;当多个字段都作为主键时,必须一起创建,称为复合主键;对于设置为主键的字段值不允许重复、不允许赋NULL值;通常把表中唯一标识记录的字段设置为主键(记录编号的字段),主键字段的标志为PRI。主键通常与auto_increment 连用 实现自增。

  2. 创建及删除主键

    		建表时创建主键:
    		
    					create table testdb.test(
    												id		int(6)	primary key,		//设置为主键
    												name	char(10),
    												group	char(10)
    											);
    							
    		在已有表中创建主键:
    		
    					alter table testdb.test add primary key (id);
    					
    		删除主键:
    		
    					alter table testdb.test drop primary;
    
  3. 创建及删除复合主键:

    		建表时创建:
    		
    				    create table testdb.test(
    				    							id			int,
    				    							name	char(10),
    				    							group	char(10),
    				    							primary key(id,name)		//创建复合主键
    				    						);
    		
    		在已有表中创建:
    		
    					alter table testdb.test add primary key(id,name);
    		
    		删除复合主键:
    		
    					alter table testdb.test drop primary key;
    

三 . 外键的使用

  1. 使用规则
    在插入记录时,字段值在另一个表的字段值范围内选择;表字段类型要一致,被参照字段必须是索引类型的一种;使用外键的前提是该表的引擎必须是innodb。

  2. 创建及删除外键

    创建外键:
    
    	create table testdb.test(
    								id			int,
    								name	char(10),
    								group	char(10),
    								foreign key(name) references 参照表名(字段名)//指定外键及参照表
    								on update cascade				//同步更新
    								on delete	cascade				//同步删除
    								)engine=innodb;					//指定存储引擎
    
    删除外键:
    
    		alter table testdb.test drop foreign key 外键名称;
    
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值