Mysql 简单增删改查 与 多表查询
单表简单增删改查
多表查询(本文通过 表sudent下的teacher_ID 与 表teacher下的ID进行关联)
- 工具 Navicat Premium
准备工作
1.新建mysql连接,名为“mysql”
2.在“mysql”下的test库下新建表student、teacher,各参数如图
3.简单插入几条数据
4.新建查询
基本语法
单表操作
查询
-- 查询学生表中的所有字段。;表语句结束, --表注释
select * from student;
-- 查询学生表中的姓名和密码
select name, password from student;
-- 查询ID为1的学生信息
select * from student where id=1;
-- 查询名字叫张三的学生
select * from student where name="张三";
-- 查询年龄大于17岁的学生
select * from student where age>17;
-- 查询你年龄大于等于17,并且年级是二年级的同学
select * from student where age>=17 and grade='二年级';
-- 查询姓李的同学
select * from student where name like '李%';
-- 查询名字中包含同字的学生
select * from student where name like '%同%';
-- 查询ID为3,4,5的学生信息
select *
from student
where ID in(3,4,5)
-- 查询tea_ID为Null与不为Null的学生信息
select * from student where teacher_ID IS Null;
select * from student where teacher_ID IS NOT Null;
增删改
插入语句
-- 向学生表中添加数据
insert into student values(6,'赵同学','213','蓝桥班',23);
-- 向学生表中添加数据,只添加用户名和密码
insert into student(name, password) values('李老师','123');
删除语句
-- 删除ID为7的学生
delete from student where ID=7;
修改语句
-- 修改学生信息,ID为8的学生密码改为123456
update student set password='123456' where ID=8;
-- 修改学生信息,把ID为6的学生年级修改为大三,年龄修改为21
update student set grade='大三',age=21 where ID=6;
单行函数
-- 最大年龄
select name, grade,max(age)
from student;
-- 最小年龄
select name, grade, min(age)
from student;
-- 平均年龄
select name, grade, avg(age)
from student;
-- 年龄和
select sum(age)
from student;
多表操作
使用等值连接,得到正确的数据
-- 查询所有信息
select *
from student s, teacher t where s.teacher_ID_ID = t.ID
-- 给表或字段起别名
select s.name stu_name, t.name tea_name
from teacher t, student s where s.teacher_ID = t.ID;
-- 查询老师所教的学生
select t.name tea_name, s.name stu_name
from teacher t, student s
where s.teacher_ID = t.ID
and t.ID=1;
-- 查询李老师所教的学生 并按学生年龄排序
-- 排序语法 order by [asc|desc] asc:正序,默认可省略 desc:倒叙,不可省略
select *
from teacher t, student s
where s.teacher_ID = t.ID
and t.ID=1
order by s.age; -- desc 倒叙
-- 查询所有学生的信息,以及关联老师信息。如果还没有选课,老师信息为空
-- 左连接 左表信息全量查询,右表与坐标匹配,没有就为NULL
select *
from student s -- 以学生表为主
left join teacher t on s.teacher_ID=t.ID;
-- 右外连 右表信息全量显示,左表与右表匹配
select *
from student s
right join teacher t on s.teacher_ID = t.ID;
-- 查询比平均年龄大的学生信息
select *
from student
where age>(select avg(age)from student);
- 左连接
- 右外连