目录
1.常用数据库命令
1.1查看所有的数据库
show databases;
1.2切换数据库
use 数据库名;
1.3查看所有的表
show tables;
1.4查看表结构
desc 表名;
describe 表名;
2.创建数据库语法
create database [ if not exists] 数据库名;
3.删除数据库语法
drop database 数据库名;
4.创建表语法
create table 表名( 字段名 数据类型 [约束|属性|注释], 字段名 数据类型 [约束|属性|注释], ... )[注释|字符];
数据类型:
整数类型:int
小数类型:double
字符类型:char(长度) varchar(长度)
日期:datetime timestamp
获取当前日期函数:now()
约束:
非空 not null
默认值 default
自动增长 auto_increment
主键 primary key
唯一键 unique key
外键 foreign key
引用 references
5.删除表语法
drop table 表名;
注意如果有主外键关系删除顺序:
1.先删从表 (有外键的表)
2.再删主表 (被外键引用的表)
6.修改表结构
6.1添加列
alter table 表名 add [column] 列名 数据类型 [约束] ;
6.2修改列
alter table 表名 change [column] 旧列名 新列名 数据类型 [约束];
6.3删除列
alter table 表名 drop [column] 列名;
4.修改表名
alter table 表名 rename [to] 新表名;
7.追加约束
7.1追加主键约束
alter table 表名 add constraint PK_约束名 primary key(列名,列名...);
7.2删除约束
alter table 表名 drop constraint 约束名;
7.3追加唯一键约束
alter table 表名 add constraint UK_约束名 unique key(列名);
7.4追加外键约束
alter table 表名 add constraint FK_约束名 foreign key(列名) references 表(列名);