庫管理
建庫操作
#創建資料庫(默認字符集編碼)
create database test20210420
#創建資料庫的時候指定字符集編碼以及字符校驗規則
create database test20210420 CHARACTER set = utf8 COLLATE utf8_general_ci
#切換可用資料庫(建表之前一定要切換)
use test20210420
#查看服務器的所有資料庫
show databases
#洗掉資料庫
drop database test20210420
#修改資料庫字符集編碼以及字符校驗規則
alter database test20210420 CHARACTER set = utf8 COLLATE utf8_general_ci
#查看資料庫資訊
show create database test20210420
表管理
建表操作
#創建表:創建表的格式
create table student( student_id int, student_name varchar(20), student_birth int )
#插入資料的命令
insert into student values(1,'姚明',20)
#查詢
select * from student
#洗掉表
drop table student
復制表操作
#結構和資料一起復制(有創建表)
create table testchar1 as select * from testchar
#結構復制(有創建表)
create table testchar2 like testchar
修改表操作
#1.給表中增加列
alter table testchar add t_age int
#2.給修改列名及列定義
alter table testchar change t_name1 t_name2 varchar(50)
#3.修改列定義
alter table testchar modify t_name2 varchar(100)
#4.洗掉列
alter table testchar drop t_age
輔助命令
#查看當前資料庫中所有的表
SHOW TABLES;
#查看表的定義資訊
SHOW CREATE TABLE testchar
#洗掉表
drop table testchar
#表重新命名
Rename table testchar to testchar3
約束:
NOT NULL:非空,該欄位的值必填
UNIQUE:唯一,該欄位的值不可重復
DEFAULT:默認,該欄位的值不用手動插入有默認值
CHECK:檢查,mysql不支持
PRIMARY KEY:主鍵,該欄位的值不可重復并且非空 unique+not null
FOREIGN KEY:外鍵,該欄位的值參考了另外的表的欄位
主鍵和唯一的異同:
區別:
①一個表至多有一個主鍵,但可以有多個唯一
②主鍵不允許為空,唯一可以為空
相同點
①都具有唯一性
②都支持組合鍵,但不推薦
主表和從表:
主表(父表)被參考欄位所在的表
在資料庫中建立的表格即Table,其中存在主鍵(primary key)用于與其它表相關聯,并且作為在主表中的唯一性標識,
從表(子表)
以主表的主鍵(primary key)值為外鍵(Foreign Key)的表,可以通過外鍵與主表進行關聯查詢,從表與主表通過外鍵進行關聯查詢,
修改表時添加或洗掉約束
#1、非空
#添加非空
alter table 表名 modify column 欄位名 欄位型別 not null;
#洗掉非空
alter table 表名 modify column 欄位名 欄位型別 ;
#2、默認
#添加默認
alter table 表名 modify column 欄位名 欄位型別 default 值;
#洗掉默認
alter table 表名 modify column 欄位名 欄位型別 ;
#3、主鍵
#添加主鍵
alter table 表名 add【constraint 約束名】 primary key(欄位名);
#洗掉主鍵
alter table 表名 drop primary key;
#4、唯一
#添加唯一
alter table 表名 add【 constraint 約束名】 unique(欄位名);
#洗掉唯一
alter table 表名 drop index 索引名;
#5、外鍵
#添加外鍵
alter table 表名 add【 constraint 約束名】 foreign key(欄位名) references 主表(被參考列);
#洗掉外鍵
alter table 表名 drop foreign key 約束名;
#自增長列
#添加自增長列
alter table 表 modify column 欄位名 欄位型別 約束 auto_increment
#洗掉自增長列
alter table 表 modify column 欄位名 欄位型別 約束
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/499436.html
標籤:MySQL
上一篇:什么是回表,怎么解決?
