工具篇:mysql(一)——key

1. primary key

表的主键,同时会建立索引。

mysql中每张table最多有一个primary key,也可以没有。primary key可以包含一个column,也可以包含多个column。当包含多个column时,这些column的组合必须在table中唯一。

2. unique key

唯一键,可以定义多个,也可以不定义。一个unique key可以包含一个column,也可以包含多个column。unique key对应列或列组合的值必须在表中唯一。

3. key

可以定义多个,也可以不定义。可以包含一个column或多个column,都可以有重复值。

information_schema.key_column_usage中可以查询每个table中primary key和unique key的constraint_name、column_name。如果包含多个column,ordinal_position记录每个column在key中的位置。

information_schema.columns可以查询每个table中各个column的信息,column_key表示该列的key属性,取值有PRI、UNI、MUL和空四种。PRI表示该列是单列主键或联合主键的一部分,UNI表示该列是单列unique key,MUL表示该列是联合unique key的第一列或联合key的第一列,或就是一个单列key。

information_schema.statistics可以查询所有key/index的信息,seq_in_index表示column_name在索引中的序号。

比如有如下table test

create table `test` (
`id` varchar(10) not null,
`name` varchar(10) not null,
`age` tinyint not null,
`staffNo` tinyint not null,
`dept` varchar(5) not null,
`team` varchar(5) default null,
`gender` varchar(5) not null,
`home` varchar(30) default null,
`zipcode` varchar(6) not null,
`company` varchar(10) not null,
key(`company`),
unique key(`zipcode`),
primary key(`name`,`age`, `id`),
unique key(`dept`,`staffNo`,`team`),
key (`gender`,`home`)
);
select COLUMN_NAME, COLUMN_KEY from information_schema.columns where  table_schema='test' and table_name = 'test'; 

select CONSTRAINT_NAME, COLUMN_NAME, ORDINAL_POSITION from information_schema.key_column_usage where table_schema = 'test' and table_name='test';

SELECT non_unique, index_name, seq_in_index, column_name  from  information_schema.STATISTICS where  TABLE_SCHEMA = 'test' and TABLE_NAME = 'test' order by INDEX_NAME, SEQ_IN_INDEX;

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值