建立資料表和修改資料表

2021-08-08 14:20:39 字數 1286 閱讀 7810

建立表

sql中建立和刪除資料庫物件的語句被稱為資料定義語言(data definition language, ddl);

操作這些物件中資料的語句被稱為資料操作語言(data manipulation language, dml)。

建立語句屬於ddl,用create table命令

create [temp|temporary] table table_name (column_definitions [, constraints]);

如果沒有生命建立臨時表,則建立的是基本表,將會在資料庫中持久存在。

column_definitions 表示乙個用逗號分隔的字段列表。每個字段定義包括乙個名稱、乙個域和乙個逗號分隔的字段約束表。

「域」一般情況下是乙個型別,與程式語言中的資料型別同名,指明儲存在該列的資料的型別。在 sqlite 中有 5 種本地型別:

integer、real、text、blob 和 null。「約束」用來控制什麼樣的值可以儲存在表中或特定的字段中。

例如,你可以用unique 約束來規定所有記錄中某個欄位的值要各不相同。

create table contacts ( id integer primary key,

name text not null collate nocase,

phone text not null default 『unknown』,

unique (name,phone) );

改變表

用alter table命令改變表的結構。sqlite中的alter table命令既可以改變表明,也可以增加字段。

格式為:

alter table table

花括號括起來乙個選項列表,必須從其中選取乙個選項。

sqlite> alter table contacts

add column email text not null default 」 collate nocase;

sqlite> .schema contacts

create table contacts ( id integer primary key,

name text not null collate nocase,

phone text not null default 『unknown』,

email text not null default 」 collate nocase,

unique (name,phone) );

約束和修改資料表

外來鍵約束 foreign key 作用 保證資料的一致性 完整性,實現一對一或一對多關係 要求 1.父表和字表必須使用相同的儲存引擎,禁止使用臨時表 2.資料表的儲存引擎只能是innodb 3.外來鍵列和參照列必須有相似的資料型別,其中數字的長度和符號位必須相同,字元的長度可以不同 4.外來鍵列和...

MySQL 修改資料表

修改資料表是指修改資料庫中已有資料表的結構。mysql 使用 alter table 語句修改表。mysql 通過 alter table 語句修改表名,語法規則如下 alter table 舊表名 rename to 新錶名 其中 to 為可選引數,使用與否均不影響結果。修改欄位的資料型別,就是把...

MySQL修改資料表

alter ignore table tb name alter spec,alter spec.alter specification add column create definition first after column name 新增新字段 add index index name i...