主鍵(建表時設置主鍵方式1):
constraint unique(id):id那一列為主鍵,任何一個id都不能相同
constraint unique(id,lastname):id和lastname兩列為主鍵,兩列都相同則不能插入,只有一列相同或者兩列都不相同則可以插入
constraint unique(id)在create table時填寫,放在最后
constraint:(約束,限定)
unique:(唯一的,獨特的)
pri=primary(主要的)
constraints 限制加入表的數據類型
eg1:創建主鍵為id的test表
create table test (id int not null, lastname varchar(255) not null,firstname varchar(255),address varchar(255),city varchar(255),constraint unique(id));
desc test;
詮釋:desc table之后列名稱key代表主鍵,里邊寫的pri則代表一個列為主鍵,pri=primary(主要的)
然后輸入兩個相同的主鍵
insert into test (id,lastname,firstname) values(1,'adams','john');
insert into test (id,lastname,firstname) values(1,'adams','john');
詮釋:id為主鍵,所以1只能出現一次
eg2:創建兩個主鍵
創建id,lastname為主鍵
create table test (id int not null, lastname varchar(255) not null,firstname varchar(255),address varchar(255),city varchar(255),constraint unique(id,lastname));
desc test;
插入:兩個主鍵完全相同的內容(第二次插入不成功)
insert into test (id,lastname,firstname) values(1,'adams','john');
insert into test (id,lastname,firstname) values(1,'adams','john');
詮釋:兩列都相同則不能插入(只有一列相同或者兩列都不相同則可以插入)
建表時設置主鍵方式2:
方式2與方式1的區別:
1、創建表時兩個方式的區別 primary key:比如id是主鍵,id不能為空 unique:主鍵可以為空
unique:撤銷唯一性
2、對應primary key(id)); constraint abcd primary key(id,lastname));
------alter table test drop primary key;只用這個撤銷
------想設置多個主鍵就要用constraint abcd primary key(id,lastname)); primary key(id));只能添加一個
3、alter table test add constraint abcd unique(id);用
------create table test (id int not null, lastname varchar(255) not null,firstname varchar(255),address varchar(255),city varchar(255),constraint abcd unique(id,lastname));
對應alter table test drop index abcd;(區別是有index)
建表后再設置主鍵:
設置一個主鍵:alter table test(表) add constraint abcd unique(id);
設置多個主鍵:alter table test add constraint abcd unique(id,lastname);
撤銷主鍵:
alter table test
null:空
not null:非空,但如果寫到create table里邊,則為空值不能寫null的意思
建表時沒有寫not null:查詢表時,空值默認顯示null
建表時對應數字的數字的列寫了not null,例如id,查詢時空值顯示:0
建表時對應字節的列寫了not null,查詢表時,空值顯示為空,什么都沒有
default:desc table時,default的意思為:默認
eg:創建id,lastname,空值不為null的test表
create table test (id int not null, lastname varchar(255) not null,firstname varchar(255),address varchar(255),city varchar(255));
desc test;
詮釋:id對應的數字顯示為0,lastname對應的字段顯示為空