mysql之主鍵,唯一,外來鍵,索引

2021-09-27 06:32:56 字數 1680 閱讀 2229

主鍵(primary key) 能夠唯一標識表中某一行的屬性或屬性組。

乙個表只能有乙個主鍵,但可以有多個候選索引。

主鍵常常與外來鍵構成參照完整性約束,防止出現資料不一致。

主鍵可以保證記錄的唯一和主鍵域非空,資料庫管理系統對於主鍵自動生成唯一索引,

所以主鍵也是乙個特殊的索引。

外來鍵(foreign key) 是用於建立和加強兩個表資料之間的鏈結的一列或多列。

外來鍵約束主要用來維護兩個表之間資料的一致性。

簡言之,表的外來鍵就是另一表的主鍵,外來鍵將兩表聯絡起來。

一般情況下,要刪除一張表中的主鍵,

必須首先要確保其它表中的沒有相同外來鍵(即該表中的主鍵沒有乙個外來鍵和它相關聯)。

索引(index) 是用來快速地尋找那些具有特定值的記錄。

主要是為了檢索的方便,是為了加快訪問速度,按一定的規則建立的,一般起到排序作用。

所謂唯一性索引,這種索引和前面的「普通索引」基本相同,

但有乙個區別:索引列的所有值都只能出現一次,即必須唯一。

總結:主鍵一定是唯一性索引,唯一性索引並不一定就是主鍵。

乙個表中可以有多個唯一性索引,但只能有乙個主鍵。

主鍵列不允許空值,而唯一性索引列允許空值。

主鍵可以被其他欄位作外來鍵引用,而索引不能作為外來鍵引用。

常用的創表語句

create table `orders` (

`id` int(11) not null auto_increment comment '無意義、主鍵uuid',

`ordernum` varchar(20) default null comment '訂單編號 不為空 唯一',

`ordertime` timestamp not null default current_timestamp on update current_timestamp comment '下單時間',

`peoplecount` int(11) default null comment '出行人數',

`orderdesc` varchar(500) default null comment '訂單描述(其它資訊)',

`orderstatus` int(11) default null comment '訂單狀態(0 未支付 1 已支付)',

`productid` int(11) default null comment '產品id 外來鍵',

`memberid` int(11) default null comment '會員(聯絡人)id 外來鍵',

primary key (`id`),

unique key `unique` (`ordernum`),

key `productid` (`productid`),

key `memberid` (`memberid`),

constraint `memberid` foreign key (`memberid`) references `member` (`id`),

constraint `productid` foreign key (`productid`) references `product` (`id`)

) engine=innodb auto_increment=10 default charset=utf8

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...

主鍵 外來鍵 唯一索引 單索引與組合索引

通過unique key 索引名稱 索引字段 using 索引方法 btree或者hash 例如對使用者表而言,使用使用者id作為其主鍵,但是作為使用者登入的使用者名稱又不能重複,但是將使用者名稱設定成主鍵,不利於後續開發,所以可以將使用者名稱設定成唯一索引,既保證了資料的唯一性,也可以提高查詢速度...

MySQL唯一約束,主鍵,外來鍵

唯一約束 新增方法 id int unique alter table customers add constraint uq unique id 刪除方法 alter table customers drop index uq 主鍵作用 primary key unique not null 新增...