mysql 資料庫、表、檢視 的建立/修改/刪除
建立,刪除資料庫 指定字符集
create database 資料庫名[default character set utf8]; (~的點 為引號)
drop database 資料庫名;
show create database 資料庫名; 檢視建立語句
alter database 資料庫名 default character set gbk;
collation 排序規則;
建立表
create table [if not exists] 表名( 欄位名 型別 [屬性 約束],
欄位名 型別 [屬性 約束],
索引,
約束)
[表選項列表];
型別[(n:長度)] [unsigned:正數] [zerofill:0填充]
uid int(4) zerofill primary key auto_increment 0001
create table 表名(
變數名1 資料型別1 約束條件11 約束條件12,
變數名2 資料型別2 約束條件2 );
not null 非空
unique 唯一
primary key 主鍵
id int primary key auto_increment 自動增加
default ‘預設值’
comment ‘欄位註釋’
parmary key (stu_id,course_id(4)); 定義多欄位主鍵
unique key [索引名](stu_id ); 唯一鍵
unique index [索引名](stu_id [asc]); 唯一索引
index [索引名] (stu_id(4),course_id); 定義索引
[constraint 約束名] foreign key (stu_id, course_id) references 表1(A, B)
外來鍵 參考 表1 主鍵
[on delete cascade onupdate casade]
外來鍵關聯主鍵刪除和更新
(表建立外來鍵 必須要有主鍵)
comment = ‘表的註釋’;
charset = 字元編碼名稱;
auto_increment = 起始整數; //自增長型別值的初值,預設是1
engine = “表的儲存引擎名”; //預設是InnoDB支援事務安全
刪除表
drop table [if exists] 表名; (先刪外來鍵,子表有資料父表不能刪)
修改表(原資料不會丟失)
alter table表名 修改語句1[, 修改語句2];
修改表名 rename to 新表名;
修改型別 位置 modify 變數名 型別 [first/after變數A];
修改列名 型別 change 變數名 新變數名 型別;
新增變數 位置 add 新變數名 型別 [約束][first/after變數A]; 默最後
新增索引/鍵 index[索名]/primary key /unique(變數1[,變數2])
constraint 約束名 foreign key(A)references表1(a)
修改預設值 alter 變數 set default ‘預設值’;
drop default ‘預設值’;
刪除變數 drop 變數名;
刪除鍵/索引 drop primary key/foreign key 外來鍵名/index 索引名;
表選項修改 omment = ‘表的註釋’;
charset = 字元編碼;
auto_increment = 起始整數; 自動增長初值,預設是1
engine = “表的儲存引擎名”;
alter table表名add constraint 約束名 foreign key(變數) references 表1(A)
on delete cascade;
主鍵值刪除時:restrict(拋異常 預設)cascade(記錄刪除)
set null(外來鍵為空) no action(什麼都不做)
插入,更新,刪除資料
insert into表1[(變數3,變數2)] values (“值31”,”值21”)[,(“值32”,null)];
insert into表1(欄位1,欄位2,) select 欄位1,欄位2 from 表2;
值的形式:數字 函式直接寫,字串時間加單引號
有以下屬性的 不應該出現該欄位名:auto_increment, timestamp,
update表名set 變數1=值/表示式,變數2=值2[where條件];
/*更新 表 中 變數1,變數2的值{滿足條件的更改}*/
delete from表名[where條件];/*刪除表中{滿足條件的}記錄*/ 事務可回滾
不刪約束,auto_increment還能繼續增長
delete from表名where 2014-year>6; 刪除過期記錄
truncate {table}表名; /*刪除表(記錄和結構)*/
複製表
create table 表B like 表A; 複製表B結構
insert into 表B select * from 表A; 插入資料
create table 表B select * from 表A; 複製結構資料 丟索引,約束,自增
load data infile ‘檔案完整名(含路徑)’ into table 表名;
載入外部“形式整齊”的資料:
索引(查詢塊 增刪改慢 佔記憶體 )
全文索引 /fulltext index 索引名(變數B ))engine=myisam;
/*型別:char,varchar,text,引擎: myisam */
空間索引 /spatial index 索引名(變數B))engine=myisam; 不為空
/*型別:geometry,引擎: myisam */
建立索引 唯一 全文 空間 普通
create [unique/fulltext/spatial] index 索引名on表名(變數名[(長)] [asc/desc]);
alter table 表名 add [unique/fulltext/spatial] index 索引名on表名(變數名);
drop index索引名on表名 刪除索引
show index from表 查看錶的索引
檢視(查詢得到的虛擬表)
表改→檢視不變,檢視改→表改
create [or replace] /alter view檢視名[(檢視變數1,檢視變數2)] as
建立 [或修改] /修改
select變數A,變數B from表名where條件
[with [cascaded/local] check dption]
/*更新[受表,檢視欄位影響/受檢視本身欄位影響]受檢視許可權限制*/
drop view [if exists] 檢視1,檢視2; [restrict/cascade] 刪除
desc 檢視名; 檢視檢視結構
show table status like ’檢視名’; 檢視檢視狀態資訊
show create view檢視名; 檢視檢視建立程式碼