绍兴优秀做网站的WordPress模仿教程
创建
create table 表名(字段1 字段类型 [约束] [comment 字段1注释],...) [comment 表注释];
 
约束是作用于表中字段上的规则,用于限制存储在表中的数据。它的目的是保证数据库中数据的正确性、有效性和完整性。
| 约束 | 描述 | 关键字 | 
|---|---|---|
| 非空约束 | 限制该字段不能为null | not null | 
| 唯一约束 | 保证字段的所有数据都是唯一、不重复的 | unique | 
| 主键约束 | 主键是一行数据的唯一标识,要求非空且唯一 | primary key | 
| 默认约束 | 保存数据时,如果未指定该字段,则采用默认值 | default | 
| 外键约束 | 让两张表的数据建立连接,保证数据的一致性和完整性 | foreign key | 
create table tb_user (id int primary key auto_increment comment 'ID,唯一标识',username varchar(20) not null unique comment '用户名',name varchar(10) not null comment '姓名',age int comment '年龄',gender char(1) default '男' comment '性别') comment '用户表';
 
MySql 数据类型

 
 
查询
-  
查询当前数据库所有表:
show tables; -  
查询表结构:
desc 表名;
 -  
查询建表语句:
show create table 表名; 
修改
-  
添加字段:
alter table 表名 add 字段名 类型(长度) [comment 注释] [约束]; -  
修改字段类型:
alter table 表名 modify 字段名 新数据类型(长度); -  
修改字段名和字段类型:
alter table 表名 change 旧字段名 新字段名 类型(长度) [comment 注释] [约束]; -  
删除字段:
alter table 表名 drop column 字段名; -  
修改表名:
rename table 表名 to 新表名; 
