SQL基本操作 新增 檢視 修改 刪除資料表

2021-07-11 06:31:23 字數 3685 閱讀 5574

1. 新增資料表

create table [if not exists] 表名(

欄位名字 資料型別,

欄位名字 資料型別 -- 最後一行不需要逗號

)[表選項];

if not exists: 如果表名不存在,就建立,否則不執行建立**。

表選項:控制表的表現

字符集:charset/character set 具體字符集; -- 保證表中資料儲存的字符集

校對集合:collate 具體校對集;

儲存引擎:engine 具體的儲存引擎(innodb和myisam)

-- 建立表

任何乙個表的設計都必須指定資料庫。

方案1:顯式的指定表所屬的資料庫

create table 資料庫名.表名(); -- 將當前資料表建立到指定的資料庫下

方案2:隱式的指定表所屬資料庫。先進入到某個資料庫環境,然後這樣建立的表自動歸屬到

某個指定的資料庫。

進入資料庫環境:use 資料庫名字;

當建立資料表的sql指令執行之後,到底發生了什麼?

1. 指定資料庫下已經存在對應的表;

2. 在資料庫對應的資料夾下,會產生對應表的結構檔案(跟儲存引擎有關係)

2. 檢視資料表

資料庫能檢視的方式,表都可以檢視。

2.1 檢視所有表:show tables;

2.2 檢視部分表,模糊匹配

2.3 檢視表的建立語句

show create table 表名;

-- 檢視表的建立語句

show create table t_student;

show create table t_student\g -- \g 等價於 ;

show create table t_student\g -- \g 將查到的結構旋轉90度,變成縱向

2.4 檢視表的結構:檢視表中的字段資訊

desc 表名/describe 表名/show columns from 表名;

3. 修改資料表

表本身存在,還包含字段。表的修改分為兩個部分:修改

表本身

和修改字段

3.1 修改表本身

表本身可以修改 

表名和 

表選項

3.1.1 修改表名

rename table 舊表名 to 新錶名;

-- 重新命名表:t_student ==> t_stu

rename table t_student to t_stu;

3.1.2 修改表選項

修改字符集,校對集和儲存引擎

alter table 表名 表選項 [=] 值;

-- 修改表選項:字符集

alter table t_stu charset = gbk;

3.2 修改字段字段操作很多:新增、修改、重名、刪除

3.2.1 新增字段

alter table 表名 add [column] 欄位名 資料型別 [列屬性][位置];

位置:欄位名可以存放到表中的任意位置

first: 第乙個位置

after: 在哪個字段之後:after 欄位名;預設是在最後乙個字段之後

-- 給學生表增加id放到第乙個位置

alter table t_stu add column id int first;

3.2.2 修改字段

修改通常是修改屬性或者資料型別

alter table 表名 modify 欄位名 資料型別 [屬性][位置];

-- 將學生表中的number學號字段變成固定長度,且放到第二位(id之後)

alter table t_stu modify number char(10) after id;

3.2.3 重新命名字段

alter table change 舊欄位 新欄位名 資料型別 [屬性][位置];

-- 修改學生表中的gender欄位為***

alter table t_stu change gender *** varchar(10);

3.2.4 刪除字段

alter table 表名 drop 欄位名;

-- 刪除學生表中的年齡字段(age)

alter table t_stu drop age;

如果表中已經存在資料,那麼刪除欄位會清空該字段的所有資料(不可逆)

4. 刪除資料表

drop table 表名1, 表名2...; -- 可以一次性刪除多張表

當刪除資料表的指令執行之後發生了什麼?

1. 在表空間中,沒有了指定的表(資料也沒有了)

2. 在資料庫對應的資料夾下,表對應的檔案(與儲存引擎有關)也會被刪除

注意:刪除有危險,操作需謹慎!(不可逆)

sql 新增 修改 刪除 約束

1.向表中新增新的字段 alter table table name add column name varchar2 20 not null 2.刪除表中的乙個字段 alter table table name drop column column name 3.修改表中的乙個欄位名 alter ...

新增 修改 刪除欄位sql語句

新增 在test table 表的 valid status 字段之後,新增乙個字段,設定對應的型別,長度,是否為null,預設值,注釋 alter table test table add column is staff tinyint 2 not null default 0 comment 是...

新增 檢視 刪除外來鍵

新增外來鍵 alter table sitecodes drop foreign key fk sitecodes 設定外來鍵 alter table 需要建立外來鍵的表 add constraint 外鍵名字 foreign key references 外來鍵表 外來鍵字段 alter tabl...