基础知识
数据库三范式
一、表中每个属性都是不可再划分的数据项
二、每张表必须存在主键
三、在满足第二范式的前提下,所有属性均不传递依赖于主键
数据类型
smallint int bigint float double
char(n) varchar(n)
date(日期) time(时间) year datetime(混合存储日期+时间)
代码展示
DOS操纵MYSQL
net start mysql80 //开启mysql80数据库
net stop mysql //关闭mysql数据库
//登录msql数据库,其中-h后边接数据库所在电脑的IP,-u后接用户名,-p后接密码
mysql -hlocalhost -uroot -p123456
基础操作
create database xxx; //创建数据库xxx
show databases; //展示所有数据库
use xxx; //使用数据库xxx
show tables; //展示所有表
insert into xxx values(......); //插入
添加约束
1.主键约束
添加:alter table table_name add primary key (字段)
删除:alter table table_name drop primary key
2.非空约束
添加:alter table table_name modify 列名 数据类型 not null
删除:alter table table_name modify 列名 数据类型 null
3.唯一约束
添加:alter table table_name add unique(字段)
4.自动增长
添加:alter table table_name modify 列名 int auto_increment
删除:alter table table_name modify 列名 int
5.外键约束
添加:alter table table_name add constraint 约束名 foreign key(外键列)
references 主键表(主键列)
删除:
第一步:删除外键
alter table table_name drop foreign key 约束名
第二步:删除索引
alter table table_name drop index 索引名
6.默认值
添加:alter table table_name alter 列名 set default '值'
删除:alter table table_name alter 列名 drop default
删除“唯一”约束
1、查看对应约束的key_name,这里用的是show index from tablename 命令,可以看到第三行,key_name为user_UNIQUE所对应即是username,这个就是我们要找的唯一性约束。
show index from week_user

2、去掉唯一约束
Alter table week_user drop index user_UNIQUE
查询表结构
1.desc / describe 表名
2.show columns from 表名
自增变量
设置自增变量:auto_increment=k,从K开始
设置自增变量步长:set @@auto_increment_increament=k,自增步长为K
查询模板
select ……
from '表名'
where '条件'
order by ……
having '条件(含聚合函数)'
group by ……
limit num1 offset num2 --num2为偏移量,num1为分页数据总量
特殊条件查询
where age not between 18 and 63
建表模板
create table student(id int primary key,
name varchar(20) not null,
gender enum("male", "female") not null);
create table report(id int primary key,
score int not null,
s_id int,
c_id int,
constraint fk_sid foreign key (s_id) references student(id),
constraint fk_cid foreign key (c_id) references course(id));
Like 运算符(模糊查询)
'_' 代表一个字符
'%' 代表一个字符串
example:
where name like '李_' --检索名字为俩字并且姓李的人
where name like '%俊%' --检索名字含‘俊’字的人
Order by 子句
asc:升序排列(默认、可省)
desc:降序排列
example:
order by grade desc --按成绩降序排列
order by sno(asc),grade desc --查询结果按学号升序排列,同一学号内按成绩降序排列
删除
删除数据:delete from '表名' where …
删除表:drop table '表名'
删除库:drop database '库名'
View视图
创建视图:create view view_name as
删除视图:drop view view_name;
权限
with grant option:用于系统权限授予,可以将自身权限授予其它用户或角色;收回权限时,传递出去的权限不会被收回,系统权限只能由dba用户回收
with admin option:用于对象权限授予,可以将自身权限授予其它用户或角色;收回权限时,传递出去的权限会随之被收回
设置别名
select name, salary * 12 as "annual salary" from employee
去重查询
select distinct department from employee
与NULL相关
可作用于NULL的比较符
<=> 安全等于
<> 安全不等于
is null is not null
ifnull(salary, 6000) --如果salary为null,则将其替换为6000
isnull(变量)
导入数据
example:
source d:\mysqldb.sql;
//未完待续
本文介绍了如何在数据库中添加和删除各种类型的约束,包括主键、非空、唯一、自动增长和外键约束,以及如何设置默认值。删除约束时需要先解除外键关联,然后删除索引。此外,还提到了查询表结构和设置自增变量的方法。
3万+

被折叠的 条评论
为什么被折叠?



