Sql語句中的DDL語句

2021-08-22 14:50:35 字數 2514 閱讀 1952

資料庫模式定義語言ddl(data definition language),是用於描述資料庫中要儲存的現實世界實體的語言。主要由create(新增)、alter(修改)、drop(刪除)和 truncate(刪除) 四個關鍵字完成。

create database 資料庫名;     //建立乙個資料庫

create database 資料庫名 default charset utf8 collate utf8_general_ci;    //建立乙個資料庫並制定編碼格式

表是存放在資料庫中的只能在資料庫下建立表

建立表時自然會用到表的約束

完整性約束條件是對字段進行限制,要求使用者對該屬性進行的操作符合特定的要求。如果不滿足完整性約束條件,資料庫系統將不執行使用者的操作。說白了,資料庫約束條件就是保證資料庫中資料的完整性。

在哪乙個資料庫下建立表首先需要切換到此資料庫下

use 資料庫名;    //使用某個指定的資料庫
在這個資料庫下建立表(關鍵字不區分大小寫)

create table 表名稱(欄位1 型別,欄位2 型別);   //在乙個資料庫中建立乙個表

create table hero_table ( id int,name varchar(10)); //建立表

//建立表並增加約束

create table 表名稱 (

欄位1 型別1 約束1 約束1,

欄位2 型別2 約束2 約束2

);//建立表並增加約束

create table hero_table4 (

id int(11) not null primary key,

name varchar(10) not null unique key

)

//只複製表結構及約束,但不複製資料

create table 複製出的表 like 原表

//複製表結構及資料,但不複製約束

create table 複製出的表 as select * from 原表

alter table 表名稱 add 欄位名 字段約束

alter table 表名稱 add column 欄位名 字段約束

alter table 表名稱 add index 索引名稱 (欄位名)
alter table 表名稱 add primary key (欄位名)

alter table 表名稱 add unique key (欄位名)

alter table 需要新增外來鍵表名稱 add foreign key 外鍵名(設為外來鍵的字段) references 被新增外來鍵表名稱(設為被新增外來鍵的字段)
alter table 表名稱 change column name 修改字段 修改為字段型別

alter table 表名稱 modify column 修改字段 修改為字段型別

//設定default

alter table 表名稱 alter column 欄位名 set default '修改的值'

//刪除default

alter table 表名稱 alter column 欄位名 drop default

//禁用約束

alter table 表名稱 disable keys

//啟用約束

alter table 表名稱 enable keys

//刪除表字段

alter table 表名稱 drop column 欄位名

//刪除主鍵

alter table 表名稱 drop primary key

//刪除索引

alter table 表名稱 drop index 索引的欄位名

//刪除外來鍵約束

alter table 表名稱 drop foreign key 外來鍵的欄位名

alter table 修改前表名稱 rename 修改後表名稱
drop database 資料庫名
drop table 表名稱
與drop的區別:truncate只刪除資料不刪除表的結構(定義),釋放空間

truncate table 表名稱;

SQL語句中對基本表的操作(DDL)

每個資料庫管理系統 database management system,dbms 對sql語句的使用基本一致,但會有稍微的差別。sql語句分為dml,ddl和dcl三類,其中dml是資料操縱語言,包括了select update insert delete 等語句,ddl為資料定義語言,包括了 c...

SQL基礎DDL語句

1,建立資料庫test1 create database test1 2,選擇資料庫test1 use test 1 3,檢視test1資料庫中建立的所有資料表 show tables 4,刪除test1資料庫 drop database test1 5,建立乙個名稱為 emp 的表。表中包括 3 ...

sql查詢語句中

sql查詢語句中select t.status,t.rowid from person t where t.status 2,此處查詢的是status不等於2的記錄,並過濾掉status為null的記錄。注意 此處不管status是integer型別還是long型別,都會過濾掉status為null...