1. 程式人生 > 其它 >MySQL中建立資料庫/表(外來鍵約束),向表中插入資料

MySQL中建立資料庫/表(外來鍵約束),向表中插入資料

技術標籤:mysql

建立資料庫/表,向表中插入資料

如果資料庫不存在則建立,存在則不建立(if not exists),也可以省略不會報錯。 建立testdate資料庫,並設定編碼集為utf8

#建立資料庫testdate;

create database if not exists test02 default charset utf8 collate utf8_general_ci;

刪除資料庫 drop database <資料庫名>;

#刪除資料庫test01
drop database test01;
#在表中新增規則

primary key #標識該欄位為該表的主鍵,可以唯一的標識記錄,主鍵就是不為空且唯一當然其還有加速查詢的作用

foreign key #標識該欄位為該表的外來鍵,用來建立表與表的關聯關係

not null #標識該欄位不能為空

unique key #標識該欄位的值是唯一的

auto_increment #標識該欄位的值自動增長(整數型別,而且為主鍵)

default #為該欄位設定預設值

unsigned #將整型設定為無符號即正數

zerofill #不夠使用0進行填充

#建立表語法 create table table01("屬性" 資料型別 not noll,...) engine=innodb default charset=utf8;不想欄位為 NULL 可以設定欄位的屬性為 NOT NULL
#AUTO_INCREMENT定義列為自增的屬性,一般用於主鍵,數值會自動加1
#其中欄位加 ·· (反引號esc下面的按鍵)是為了區分關鍵字 也可以不用加,也可以執行成功
#其中設定 id(要唯一,不能重複) (primary key主鍵,auto_increment自增)
#建立students,以id為主鍵
create table `students`(
`id` int(10) not null auto_increment primary key,
`snames` varchar(10) not null,
`班級` varchar(10) not null
, `出生日期` date )engine=innodb default charset=utf8;
#建立成績表grade_table,關聯students表中外來鍵
create table grade_table(
g_id int(10) not null auto_increment,
sname varchar(10) not null,
garde int(10) not null,
rank varchar(10) not null,
constraint fk_id foreign key (g_id) references students(id)

on update cascade #更新同步
on delete cascade #刪除同步
)engine=innodb default charset=utf8;;

#fk_id 為外來鍵約束索引,外來鍵名稱為 g_id,其依賴於表 students 的主鍵 id。
#刪除資料表:drop table <table_name>;
drop table `grade_table`;
#使用truncate 清空資料表不會進行刪除操作
truncate table students;
向表中插入資料

#插入資料語法:insert into 表名(列1,列2,列3,。。。,列n)values(value1,value2,。。。valuen),…,(。。。);

#在students表中插入三行資料
insert into students (id,snames,班級,出生日期)
values
(8,'小明','一班','2010-12-08'),
(7,'小鄭','二班','2008-06-18'),
(10,'小紅','三班','2009-11-08');
#所有列進行新增資料的話,可不用把所有列寫出來;如下在students表中搽插入id=12的一行資料
#在students中插入一行資料,注意id不能有重複
insert into students values (12,'小藍','三班','2011-10-08');
#在grade_table表中插入三行資料

insert into grade_table(g_id,sname,garde,rank)
values
(8,'小明',70,'B'),
(7,'小鄭',90,'A'),
(10,'小紅',60,'C');

students表:

在這裡插入圖片描述

grade_table表
在這裡插入圖片描述