文章目录
学习
启动数据库 net start mysql版本号
连接数据库 mysql -h localhost -u root -p
数据库定义语言DDL
show databases;//查询
create database 数据库名称 //创建数据库
create database if not exisits 数据库名称 //判断,如果不存在则创建
drop database 数据库名称// 删除
drop database if not exisits
select database() //查看当前使用的数据库
use 数据库名称 // 使用数据库
数据库操作语言DML
insert into 表名(列名1,列名2,……) values(值1,值2,……) //增加
update 表名 set 列名1=值1,列名2=值2,…… where 条件//修改
delete from 表名 where 条件 //删除
数据库查询DQL
去除重复记录
select distinct 字段列表 from 表名
条件查询
between …… and …… 在某个范围之内(都包含)
IN(……) 多选一
LIKE 占位符 模糊查询 _单个任意字符 %多个任意字符
排序查询
select 字段列表 from 表名 order by 排序字段名1【排序方式】 , 排序字段名2【排序方式】 ,
order by // asc 升序 desc 降序
分组查询
groud by
聚合函数 (将一列数据作为一个整体,进行纵向计算)
count . max . min . sum . avg
select sex , avg(math),count(*) from stu where math > 70 group by sex having count(*) >2;//查询男女同学各自的数学平均分,以及各自人数,要求;分数低于70分的不参与分组,分组之后人数大于2
//having 分组后条件过滤
分页查询
select * from stu limit 0,3;//从0开始查询,查询3条数据
select * from stu limit 0,3
数据库定义语言 DDL
数据库控制语言 DCL
事务控制语言 DCL
约束
非空约束 not null
唯一约束 unique
主键约束 primary key
检查约束 check 保证列中的值满足某一条件
默认约束 default
外键约束 foreign key : constraint 外键名 foreign 外键列名 references主表名
auto_increment 自增
alter table 表名 modify 字段名 数据类型 not null // 添加非空约束
alter table 表名 modify 字段名 数据类型 default//删除约束
alter table 表名 add constraint 外键名称 foreign key 外键字段名 references 主表名称 //添加外键约束
alter table 表名 drop foreign key 外键名
数据库设计
多对多表关系: 建立第三张中间表,至少包含两个外键,分别关联两方的逐渐
create table tb_goods(
id int primary key ,
title varchar(100),
price double(10,2)
);
create table tb_order(
id int primary key auto_increment,
payment double(10,2),
payment_type tinyint,
status tinyint
);
create table tb_order_goods(
id int primary key auto_increment,
order_id int,
goods_id int,
count int
);
alter table tb_order_goods add constraint fk_order_id foreign key (order_id) references tb_order(id);
alter table tb_order_goods add constraint fk_goods_id foreign key (goods_id) references tb_goods(id);
多表查询
内连接
select *from emp ,dept where emp.dep_id = dept.id;//隐式内连接
select * from emp inner join dept on emp.dep_id = dept.id;//显式内连接
外连接
select * from a left join b on a.b_id = b.id ; //左外连接 查询a表所有数据以及交集
select * from a right join b on a.b_id = b.id;//右外连接
子查询 查询中嵌套查询
select 字段列表 from 表 where 字段名 = (子查询);//单行单列
select 字段列表 from 表 where 字段名 in (子查询);//多行单列
select 字段列表 from (子查询) where 条件;//多行多列
事务
开启事务 begin
提交事务 commit
回滚事务 rollback
练习
编写一个 SQL 查询,查找所有至少连续出现三次的数字。
返回的结果表中的数据可以按 任意顺序 排列。
distinct
select distinc l1 from logins where...
在表中,可能会包含重复值。(distinct)可以使结果值只出现一次
关键词 DISTINCT 用于返回唯一不同的值。
请你编写一个 SQL 查询来交换所有的 ‘f’ 和 ‘m’ (即,将所有 ‘f’ 变为 ‘m’ ,反之亦然),仅使用 单个 update 语句 ,且不产生中间临时表。
两个相等的数异或的结果为 0,而 0 与任何一个数异或的结果为这个数。
将 sex 字段和 'm' ^ 'f' 进行异或操作,最后就能反转 sex 字段。
update salary
set
sex = char(ASCII(sex)^ASCII('m')^ASCII('f'));
表连接 左连接和右连接 left join and right join
select
FirstName,LastName,City,State
from
Person p1
left join
Address a1
on
p1.PersonId=a1.PersonId;