MYSQL数据库详解(2)
库操作
查看所有库
show databases;
创建库
#格式: create database 库名
create database java_newsql;
create database javaee2307;
删除库(危险操作)
– drop database 库名
drop database javaee2307;
使用库 / 切换库
格式:use 库名
use javaee2307;
表操作
查看库中的所有表
show tables;
创建表
格式:/*
create table 表名(
字段名 字段类型,
字段名 字段类型
)
*/
create table teacher(
tid char(6),
tname varchar(10),
tsex char(1),
tmoney decimal(10,2),
tbir datetime
)
– 字符串sql表示方式 ‘’ “”
#comment 注释
create table teacher2(
tid char(6) comment '编号',
tname varchar(10) comment "姓名",
tsex char(1) comment '性别',
tmoney decimal(10,2) comment '工资',
tbir datetime comment '出生日期'
)
查看表结构
方式一:
desc teacher2;
方式二:
show create table teacher2;
反义符 `` 反义关键字
#DEFAULT NULL 默认的值(null为类型)
/*
CREATE TABLE `teacher2` (
`tid` char(6) DEFAULT NULL COMMENT '编号',
`tname` varchar(10) DEFAULT NULL COMMENT '姓名',
`tsex` char(1) DEFAULT NULL COMMENT '性别',
`tmoney` decimal(10,2) DEFAULT NULL COMMENT '工资',
`tbir` datetime DEFAULT NULL COMMENT '出生日期'
)
存储引擎(规则)
ENGINE=InnoDB
字符集
DEFAULT CHARSET=utf8mb4
字符顺序
COLLATE=utf8mb4_0900_ai_ci
*/
查看存储引擎
show engines;
修改表结构
格式:alter table 表名 关键词 属性
修改表名
alter table teacher2 rename as student;
表添加字段
alter table student add qq varchar(12) comment 'QQ号';
删除一个字段(危险操作)
alter table student drop tmoney;
修改字段
1.modify – 覆盖式,只能修改类型和属性
alter table student modify qq varchar(20);
2.change – 覆盖式,字段名,类型,属性都可以修改
alter table student change qq weixin varchar(50) comment 'weixin号';
特殊修改情况
1.将类型的长度减小
2.将类型修改成其他的类型
删除表
drop table student;
约束
非空约束 not null
create table tab2(
name varchar(10) not null, -- 非空约束
age int
)
唯一约束 unique
create table tab3(
name varchar(10) unique, -- 行级约束
age int
)
create table tab4(
name varchar(10),
age int,
sex char(1),
unique(name,age,sex) -- 表级约束
)
create table tab5(
name varchar(10),
age int,
sex char(1),
-- 表级唯一约束命名 constraint关键字
constraint unique_name_age_sex unique(name,age,sex)
)
主键约束
create table tab6(
id int primary key, -- 主键约束
name varchar(10),
age int,
sex char(1)
)
create table tab8(
id int,
name varchar(10),
age int,
sex char(1),
primary key(id,name) -- 表级主键约束(联合约束)
)
# auto_increment 自增
create table tab9(
id int primary key auto_increment, -- 自增的主键约束
name varchar(10),
age int,
sex char(1)
)
primary key 和not null unique的区别
- 一个表只能设置一个主键,not null unique可以设置多个
2.逻辑上的主键标识
外键约束 foreign key (外键字段) references 表名(字段)
一个表中可以有多个外键约束
创建先创建父表
删除先删除子表数据
插入先插入父表数据
#子表
create table a(
aid int primary key auto_increment, -- 自增的主键约束
name varchar(10),
bid int, -- 外键
foreign key (bid) references b(bid) -- 外键约束
)
#父表
create table b(
bid int primary key auto_increment, -- 自增的主键约束
name varchar(10)
)