基础表操作
#连接数据库
# -u 用户
# -p 密码
# -P 端口号,默认3306
# -h host,默认本地
mysql -p -u
#查看数据库,命令行中加分号结束,而不是回车
show databases;
#创建数据库
create database {database_name};
#删除数据库
drop database {database_name};
# 切换数据库
use {database_name};
# 创建表,后面跟的是列定义: (列名 数据类型 [列约束])
create table {table_name} (id int(11) preimary key auto_increment,name varchar(32) not null default 'xxx',password varchar(32) not null);
#显示表,这里是tables,而不是table,容易错
show tables;
#删除表
drop table {table_name};
#插入数据
insert into {table_name} name,password values ('aa','aa'),('bb','bb'),('cc','cc'),('dd','dd');
#查看表定义
describe 表名;
#简写
desc 表名;
# 查看表详细结构,会展示建表语句,数据引擎信息,\G让展示额数据更好看
show create table 表名\G;
# 修改表名
alter table 旧表名 rename to 新表名;
# 修改表中的字段类型
alter table 表名 modify 字段名 数据类型;
#修改字段名
alter table 表名 change 字段名 新字段名 新数据类型;
# 添加字段
alter table 表名 add 字段名 数据类型 [约束条件] [first|after 现有字段名];
# 删除字段
alter table 表名 drop 字段名;
# 修改字段排序
alter table 表名 modify 字段名 数据类型 [first|after 现有字段名];
#修改表的存储引擎
alter table 表名 engine=引擎名;
# 查看支持的引擎
show engines\G;
#删除外键约束
alter table 表名 drop foreign key 外键约束名
#删除表(有从表先删除从表)
drop table [if exists] 表1,表2...
#
列约束(https://www.jianshu.com/p/a912bb60052e)
- 主键约束 primary key
- 外键约束
constraint <外键约束名> foreign key 字段名1[,字段名2,...] references <主表名> 主键列1[,主键列2,...] - 非空约束 not null
- 唯一性约束 unique
- 默认约束 default xxx
- 自动增加 auto_primary
这个是下划线不是空格
只能是整数类型