mysql管理主鍵的表 Mysql的學習3

2021-10-18 11:50:40 字數 2516 閱讀 3824

1.主鍵:

每個表中最多只能有1個主鍵,且主鍵的值不能重複,通過主鍵可以唯一的確定一條記錄。當我們在建立表的時候就宣告了主鍵的話,mysql就會對我們插入的每一條記錄進行檢驗,若有主鍵值相同時就會報錯。另外主鍵是預設notnull的。

宣告主鍵的兩種方式:

主鍵只是單個列時(比如設定學生的學號為主鍵):

stu_id   int( 5 )  primary key;

主鍵是多個列時  :

primary key(列名1,列名2。。。);

主鍵和唯一性約束的區別:

都保證了列或列組合的唯一性;但是主鍵在乙個表中只能有乙個,唯一性約束可以存在多個;主鍵不允許為空,唯一性約束可以為空的。

2.外來鍵:

定義:在兩個關係中存在公共的若干個字段,且在乙個關係中這些公共欄位是主鍵就稱該錶為主表,另乙個關係就稱為從表並稱這些公共欄位為外來鍵。外來鍵主要目的是將兩張表形成關聯,即就是可以通過從表的外來鍵來引用從表中其他列的值或者空值。

定義的語法格式:

constraint   [ 外來鍵的名稱 ]   foreign  key (列1,列2。。。) refferences  父表名(父列1,父列2。。。)

(建立外來鍵時:先建立主表,再是從表     刪除外來鍵時:先刪除從表,再是主表)

#建立外來鍵方式:在建立從表的同時建立外來鍵

(grade是主表,student是從表)

create table `grade` (

`gradeid` int(10) not null auto_increment comment '年級id',

`gradename` varchar(50) not null comment '年級名稱',

primary key (`gradeid`)

) engine=innodb default charset=utf8;

create table `student` (

`studentno` int(4) not null comment '學號',

`studentname` varchar(20) not null default '匿名' comment '姓名',

`***` tinyint(1) default '1' comment '性別',

`gradeid` int(10) default null comment '年級',

`phonenum` varchar(50) not null comment '手機',

`address` varchar(255) default null comment '位址',

`borndate` datetime default null comment'生日',

`email` varchar(50) default null comment '郵箱',

`idcard` varchar(18) default null comment '身份證號',

primary key (`studentno`),

key `fk_gradeid` (`gradeid`),

constraint `fk_gradeid` foreign key (`gradeid`) references `grade` (`gradeid`)

) engine=innodb default charset=utf8;

3.資料的管理:

資料庫操作語言:用於運算元據庫物件中所包含的資料。

insert:新增資料語句

語法:insert  into  [ 表名 ]  (列1,列2。。。) value (值1,值2。。。);

insert into `school`.`grade`(`gradeid`,`gradename`) value ('7','大六');     (注意資料庫名,表名,欄位名用 ` ` 括起來,普通的字串用 ' '括起來)

insert into `school`.`test` (`coll`) value ('row1'),('row2'),('row3');   (多行插入)

update:更新資料語句

update `school`.`grade` set `gradename`='工科實驗班',`gradeid`='100' where `gradeid`='5';

語法:update  表名  set 列名1=值1,列名2=值2 where 列=目標列

列名為要修改的列, where後面是具體的條件,略寫時指在修改所有列的資料

delete:刪除資料語句

delete from `school`.`grade` where `gradeid`='8';

語法:delete from 表名 [where condition];

注意:condition為篩選條件,如果不指定則刪除表的所有列資料

truncate:用於完全清空表資料,表結構,索引,約束等不變,不會對事務有影響

刪除後自增的當前值會從初始值開始重新記錄。

truncate table `school`.`grade`;

語法:truncate [table] table_name;

mysql建表,主鍵,等

1 最簡單的 create table t1 id int not null,name char 20 2 帶主鍵的 a create table t1 id int not null primary key,name char 20 b 復合主鍵 create table t1 id int no...

mysql刪除及更改表的主鍵

在我們使用mysql的時候,有時會遇到需要更改或者刪除mysql的主鍵,我們可以簡單的使用alter table table name drop primary key 來完成。下面我使用資料表table test來作了例子。1.首先建立乙個資料表table test create table ta...

mysql表的管理

表字段操作 1.建立表 create table 表名 id int,name varchar 15 age int,score float 2.修改表字段 新增字段 alter table 表名 add 欄位名 資料型別 first after 刪除字段 alter table 表名 drop 欄...