MySQL 資料表操作

2021-09-26 04:40:57 字數 3028 閱讀 8953

重新命名表

複製表刪除表

格式:create [tempoprary] table [if not exists] 表名

[(create_definition,…))][table_options][select_statement];

引數說明:

關鍵字說明

create_definition

表的列屬性。要求建立表時,至少包含一列。

格式:col_name type[not null | null][default default_value][auto_increment][primary_key][reference_definition]

table_options

表的屬性。一般來說用於選填表將如何儲存,並且儲存在何處。例如engine選項用於定義表的儲存引擎。

select_statement

select語句。一般用於快速建表。

例:

檢視表結構分別有兩種方式:

1.show [full] columns from 表名;

2.describe 表名;或者縮寫desc 表名;

例:

修改表結構均使用alter table語句。修改表結構指增加字段或者刪除字段、修改欄位名稱或者字段型別、設定或者取消主鍵和外來鍵、設定或者取消索引以及修改表注釋等,語法如下:

alter [ignore] table 資料表名 alter_spec[,alter_spec]…| table_options;

其中[ignore]為可選項,表示如果出現重複關鍵的行,則只執行一行。其他重複行被刪除。alter_spec為需要修改的內容,以下為alter_spec的語法格式列表:

alter_spec 內容

說明add [column] create_definition [first |after col_name]

新增新字段

add index [index_name] (index_col_name,…)

新增索引名稱

add primary key (col_name)

新增主鍵名稱

add unique [index_name](index_col_name)

新增唯一索引

alter [column] col_name

修改字段預設值

change [column] old_col_name create_definition

修改字段定義(欄位名、型別)

modify [column] create_definition

修改子句定義字段

drop [column] col_name

刪除字段

drop primary key

刪除主鍵

drop index index_name

刪除索引

rename [as] new_tbl_name

修改表名

其中指設定預設值或者刪除預設值,literal為指定的預設值。

alter table 語句允許指定多個動作,其動作間使用逗號分隔,每個動作表示對錶的乙個修改。

例:

例:

例:

例:

格式:rename table 舊表名 to 新錶名;

例:

在一張已經存在的表的基礎上,複製一張表結構甚至表資料相同但表名不同的表,即複製表。有兩種格式:

create table [if not exists] 資料表名 ;

其中是必選項,指要從哪個源資料表來建立副本。

例:

create table … like 方式複製的新錶,資料不複製。例:

使用這種方式複製表時,只會建立乙個與源資料表有相同的表結構、列名、資料型別、索引的副本,但是並不會複製源資料表中的資料。若要同時複製表資料,可用as子句來實現。

as子句方式複製表:create table 表名 as select * from 源資料表;該方式可同時複製源表的結構和源表的資料,例:

格式:drop table 表名;

例:

MySQL資料表操作

建立資料表 create table 資料表名示例 create temporary table if not exists 資料表名 col name type 完整性約束條件 col name type 完整性約束條件 table options select statement 建立使用者表 ...

MySQL資料表操作

目錄 資料表介紹 資料表列出 列出當前資料庫的所有資料表 建立資料表 指定資料庫建立表 在當前開啟的資料庫中建立表 建立表時指定校對集 查詢表詳情 指定資料庫查詢表建立資訊 在當前開啟的資料庫中查詢表建立資訊 查詢表詳情 show 查詢表詳情 desc 資料表修改 修改表名稱 修改表字符集 資料表刪...

Mysql資料表操作CRUD

一 建立資料表 1 建立表 create table student id int 11 not null auto increment,name varchar 20 not null,age int 11 not null,score double 4,1 not null,borthday d...