添加数据
insert user (account,password) values("hbu","123"),("yyf","123");
修改数据
update user set account = "yyf";-- 全部修改
update user set account="yyf" where id="1"; -- 选择修改
update user set account="yyf",password="123321" where id="1"; -- 多项修改
删除数据
-- 删除数据 delete from user where id="7"; -- 不加条件就是全部删除
查询数据
select id,account,password from user; -- * 代表所有字段,可以带条件查询 select * from user where id=7; -- 可以使用as来取别名,可以省略用空格代替 select id as "唯一值" from user; -- 排序order by asc(升序) desc(降序) 默认升序 select * from student order by age desc;
多条件查询 and / or
select * from user where id=7 or id=5 and password=123456;
范围查询 in(),字段 between 值1 and 值2
select * from user where id in(9,10,11); select * from user where id between 10 and 20;
去重查询 distinct
select distinct account,`password` from user;
MySQL中将关键字设置为变量最好使用 `` 来标记一下
模糊查询 like 同时需要使用通配符 %(任意字符) _(一个字符)
select * from user where account like "熊%" select * from user where account like "%熊%"
限制查询(limit 0,3)或者(limit 3 offset 0)其中0代表从0索引,3表示找3条数据 应用:利用限制查询做分页操作 (一页显示五条)
select * from student limit 0,3; select * from student limit 3 offset 0; -- 一页五条 select * from student limit 0,5; select * from student limit 5,5;
聚合查询
查询数值量 count()
select count(*) from student;
求平均值 avg()
select avg(age) from student;
总数 sum()
select sum(age) 年龄总数,count(*) 学生个数,avg(age) 平均数; -- 最好使用英文做表头
最大值 max()
select max(age) from student
最小值 min()
select min(age) from student
分组查询 group by having分组之后的条件 where 分组之前的条件
select sex,count(*) from student group by sex
多表查询
-- 全连接(笛卡尔积) 很少使用
select * from student,class
-- 等值查询
select student.id,`name`,sex,age,sno,class_name from student,class where student.class_num = class.class_num and `name`="李四"
-- 自连接
select * from class t1,class t2 where t1.id = t2.id
-- 连接查询 内连接inner join,左连接 left outer join,右连接right outer join
select * from student inner join class on student.class_num = class.class_num where class_name="电子信息工程"
三种连接方式
-- 子查询(嵌套查询)
select class_num from class where class_name=(select class_num from class where class_name="数学")
多表关系
- 一对一关系 —— 方案一最优:合并同一表;方案二:将一个表的id存在另一个表里产生对应关系;方案三:把双方的id拿出来重新做成一个表,从而达到一对一对应。
- 一对多关系 —— 一个总内容表(例班级)指向一个小内容表(例学生)。方案一:小内容表指向大内容表的id;方案二:做中间表,id对应
- 多对一关系 —— (员工与部门)相当于一对一
- 多对多关系 —— 中间表