通過unique key 索引名稱(『索引字段』) using 索引方法(btree或者hash),例如對使用者表而言,使用使用者id作為其主鍵,但是作為使用者登入的使用者名稱又不能重複,但是將使用者名稱設定成主鍵,不利於後續開發,所以可以將使用者名稱設定成唯一索引,既保證了資料的唯一性,也可以提高查詢速度。-- ----------------------------
-- table structure for user
-- ----------------------------
drop
table
ifexists
`user`;
create
table
`user` (
`id`
int(11) not
null auto_increment comment '主鍵',
`username`
varchar(255) not
null comment '使用者名稱',
`password`
varchar(255) not
null comment '密碼',
primary
key (`id`),
unique
key`username` (`username`) using btree comment '建立使用者名稱的唯一索引,索引方法使用btree(也可以使用,hash)'
) engine=innodb default charset=utf8;
-- ----------------------------
-- records of user
-- ----------------------------
單索引可以加快該字段的檢索速度,但是與唯一索引不同的是,單索引並不限制,索引不能重複。建立單索引的方式create index 索引名 on 表名(欄位名),例如要給上面user表的username建立單索引可以以下面的方式建立。create index username on
user(username)
組合索引的建立方式為create index 索引名 on 表名(欄位名1,欄位名2),如給user表的username與password建立組合索引的方式如下所示: 對於組合索引而言,可以直接快速的查詢出位址在北京年齡為25的使用者。create index user_name_pwd on
user(username,password)
可想而知,在實際使用過程中,要根據實際應用場景選擇建立索引的方式,如果只是為了快速查詢單個字段,則使用單索引,若果需要使用多個字段進行查詢分析,則使用組合索引,如果要保證資料的唯一性使用唯一索引。
Oracle 主鍵外來鍵唯一索引索引
1.查詢索引 select table name,index name from user indexes where table name upper test temp1 2.建立主鍵 1 建立表的時候建立 create table test temp1 id int primary key,n...
mysql之主鍵,唯一,外來鍵,索引
主鍵 primary key 能夠唯一標識表中某一行的屬性或屬性組。乙個表只能有乙個主鍵,但可以有多個候選索引。主鍵常常與外來鍵構成參照完整性約束,防止出現資料不一致。主鍵可以保證記錄的唯一和主鍵域非空,資料庫管理系統對於主鍵自動生成唯一索引,所以主鍵也是乙個特殊的索引。外來鍵 foreign ke...
索引 主鍵 外來鍵
參 索引的優點 加快查詢表記錄的速度。索引的缺點 會減慢寫的速度 如 insert update 占用物理儲存空間。2 簡述普通索引與主鍵的約束規則。參 1 index普通索引 乙個表中可以有多個index欄位 欄位的值允許有重複,且可以賦null值 經常把做查詢條件的字段設定為index欄位 in...