MySQL在Navicat Premium中的基本操作
一、建表
1.创建表格

右击表格,建立新表,按主ctrl+s修改表名称为student
2.增添表格项
这里添加了id(用户ID) name(学生姓名) pass(登陆密码) grade(学生年级) age(学生年龄) tea_id(授课老师ID)
类型都有默认类型,根据个人需要进行选择,int为整型,varchar为字符串类型,长度根据自己要求进行设置,勾选了不是null表示该栏不允许不填,最后金钥匙表示为主属性
注意,ID勾选自动递增
点击保存
3.填充表格—直接填充

点击创建好的student表格,进行填充
想再次进行表格属性调整可以右击student点击调整表格
同样的方法创建一个teacher表格

id(用户ID)name(教师姓名)course(教课类型)teach_age(教龄)
二、通过MySQl语句对数据库表进行操作
1.创建查询

点击查询,按ctrl+s重命名表格为sqltest
2.sql语句注释
-- 该处为注释
3.查询学生表信息
注:‘;’代表sql语句结束
查询学生表所有内容,*代表查询表格中所有内容
select * from student;
选中语句右击,点击运行选择语句
查询学生表中姓名和密码
select name,pass from student;
查询某一个学生的信息:id为1
select * from student where id = 1;
查询名字为刘琛的信息
SELECT * FROM student where name = '刘琛';
查询年龄大于11的
SELECT * FROM student where age > 11;
查询年龄大于11并且年级是一年级的同学,and连接两个条件
SELECT * FROM student where age > 11 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);

查询老师id为null的学生信息is null, 非空 is not null
select * from student where tea_id is null;

4.向学生表中添加数据–sql语句添加
向学生表中添加数据
insert into student values(7,'李林志','123','蓝桥班',21);
向学生表中只填加用户名和密码
insert into student(name,pass) values('姜晨宇','123');
5.删除数据
删除数据
delete from student where id = 7;
6.修改学生表中数据
修改学生信息,将id为9的数据密码修改为123456
update student set pass = '123456' where id = 9;
注:注意不要落下条件,没有条件会对表中所有数据进行修改
修改学生信息把id为6的学生,年级修改为大三,年龄修改为22;
update student set grade = '大三',age = 23 where id = 6;
三、多表查询
1.多表查询,根据student.tea_id = teacher.id
之前的操作只是对student表格或者teacher表格单独进行的操作,接下来通过student表格的tea_id进行连接
多表查询,查询老师以及对应老师的信息
select *
from student,teacher
where student.tea_id = teacher.id;
2.给多表起别名
给表格起别名,student s,将student表格取别名为s,select s*代表取s表格全部,t.name
tname戴白哦取t表格name,并且取别名为tname
select s.*,t.`name` tname
from student s,teacher t
where s.tea_id = t.id;
3.根据特定信息查询
吕老师教的学生
SELECT t.*,s.*
FROM student s,teacher t
where s.tea_id = t.id
and t.name = '吕老师';

查询杨老师教的学生,并且按照年龄排序—>order by , desc表示倒序,asc 表示正序默认可省略
SELECT t.*,s.*
from student s,teacher t
where s.tea_id = t.id
and t.name = '杨老师'
order by s.age desc;

4.左连接,右连接
左连接left join 需要加入的表格 , on 条件
查询所有学生信息,以及关联的老师信息,如果没有选课显示为null(学生表为主)
select *
from student s
left join teacher t on s.tea_id = t.id;
右连接(老师表为主)
select *
from student s
right join teacher t on s.tea_id = t.id;
四、子查询
1.对age求平均,求和,求最大,求最小
对age avg平均值 ,sum求和,max最大值,min最小值
SELECT AVG(age)
from student s;

2.求比平均年龄大的学生信息
查询比平均年龄大的学生的信息
SELECT *
from student
WHERE age>(select avg(age) from student);