MySQL基本命令(增刪改查,check約束)總結:


表字段的增,刪,改,查:

:alter table 表名 add 字段名 數據類型 【位置】

:alter table 表名 drop 字段名;

:alter table 表名 modify 字段名 數據類型 【位置】;

重命名: alter table 表名 change oldname newname 數據類型 【位置】;

查看表結構:desc 表名;

查看所有表:show tables;

查看部分表:show tables like ‘表名’;

 

數據的增,刪,改,查:

insert into 表名 values(值1,值2,……);

insert into 表名 (字段1,字段2……)values(值1,值2.……);

: delete form 表名 where 條件;/ truncate 表名;

:update 表名 set 字段=‘值’ 【where 條件】;

:select */字段列表 form 表名 【where 條件】

表的增,刪,改,查:

創建表:create table 表名();

刪除表:drop table 表名稱;

改表名:alter table 表名rename 新表名;/rename table表名 to 新表名;

查表

查看當前數據庫的所有表格:show tables;

查看某數據庫的所有表格:show tables from 數據庫名;

 

數據庫的增,刪,改,查:

創建數據庫:create database 數據庫名 / create database 數據庫名 charset=utf8;

刪除數據庫:drop database 數據庫名;

選擇數據庫:use 數據庫名;

查看當前正在使用的數據庫:select database();

查看有哪些數據庫:show databases;

 

約束:

check檢查約束

在插入性別時,只能插入男或女,或者將數據控制在一定范圍

check檢查約束也可以使用enum類型或者觸發器

enum:

添加性別字段對其進行約束:alter table 表名 add gender enum(‘男’,‘女’,‘未知’);

 

鍵約束:主鍵約束,外鍵約束,唯一鍵約束

Not NULL約束:非空約束

check約束:檢查約束

default約束:缺省約束

 

主鍵約束(primary key)相當於唯一約束+非空約束的組合

不允許出現重復,也不允許出現空值

每個表只允許出現一個主鍵約束,一般跟在字段名后

刪除主鍵約束后,非空還存在:alter table 表名稱 drop primary key;

 

唯一鍵(unique key)簡稱UK

同一個表中可以有很多個唯一約束

會默認創建一個唯一索引

也是直接跟在字段名后

 

外鍵(forgin key)簡稱FK

用於兩個表的兩個字段之間的參照關系

保證一個或兩個表之間的參照完整性

在從表上建立外鍵,而且主表要先存在

從表的外鍵列,在主表中引用的只能是鍵列(主鍵,唯一鍵,外鍵)

外鍵一定是在從表中創建,從而找到與主表之間的聯系

添加外鍵進行關聯:alter table 表明 foreign key(從表字段名) references 表明(主表字段名);

 

 

判斷存在就刪除然后創建

creata table if exists 表名  

drop table if exists 表名

創建臨時表

create temporary table 表名

mysql自增長

auto_increment

添加外鍵約束

alter table 表名 add constraint fk_引用id foreign key(引用id) references 被引用表名 (被引用id)

添加主鍵約束

alter table 表名 add constraint pk_id primary key (id);

刪除約束

alter table 表名 drop forign key fk_引用id

添加表的字段

alter table 表名 add 字段名 類型 ;

修改表中的字段為空

alter table 表名 modify 字段名  類型  null

修改表中的字段不為空

alter table 表名 modify 字段名  類型 not null

添加表的字段自增主鍵

alter table 表名 add column 字段名 類型 auto_increment not null, add primary key(cid);

刪除表的字段

alter table 表名 drop column 字段;

刪除表的主鍵

alter table 表名 drop primary key;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM