流程控制语句
if和case语句
select if(tb_emp.gender = 1 , '男', '女') 性别, count(*) from tb_emp group by gender ;
select (case job when 1 then '班主任' when 2 then '讲师' when 3 then '教学主管' when 4 then '教务处' else '未知' end) ,count(*) from tb_emp group by job ;
表和表的关系
1.一对一
假设a表和b表一一对应,如果要在数据库实现这个功能 只需要在a表或者b表找一个外键和一个表的主键相关联
2.一对多
假设a表:b表 = 1:n 如果要在数据库实现这个功能 需要在b表中找一个外键和a表中的主键相关联
3.多对多
假设a表和b表是多对多的关系 需要创建一个a表和b表的联合表 该表命名为c表,令c表包含两个外键联系a表和b表的主键
多表查询
内连接 语句
select tb_emp.name '员工姓名' ,tb_dept.name '部门名称' from tb_emp , tb_dept where tb_emp.dept_id = tb_dept.id ; select tb_emp.name '员工姓名' ,tb_dept.name '部门名称' from tb_emp inner join tb_dept on tb_dept.id = tb_emp.dept_id ; select e.name , d.name from tb_emp e , tb_dept d where e.dept_id = d.id ;
左连接查询(查询包括所有左表)
select e.name '员工姓名', d.name '部门名称' from tb_emp e left join tb_dept d on e.dept_id = d.id ;
右连接查询(查询包括所有右表)
select e.name '员工姓名', d.name '部门名称' from tb_emp e right join tb_dept d on e.dept_id = d.id ;
子查询包括标量子查询
标量子查询 :子句中仅返回一个值
select *from tb_emp where dept_id = (select tb_dept.id from tb_dept where id=2) ;
select * from tb_emp where entrydate > (select tb_emp.entrydate from tb_emp where id = 3) ;
列子查询:子查询的返回值是一列(可以是多行)
select *from tb_emp where dept_id in ( select tb_dept.id from tb_dept where name in ('学工部','教研部') );
行子查询:子查询返回值是一行(可以是多列)
select *from tb_emp where (entrydate,job) =
(select tb_emp.entrydate , tb_emp.job from tb_emp where name='韦一笑') ;
表子查询:子查询的返回值是一个表
# 查询入职日期是2006-01-01之后员工的信息以及部门名称
select e.* ,d.name from
(select * from tb_emp where entrydate > '2006-01-01' ) e ,
tb_dept d
where e.dept_id = d.id ;
-- 1. 查询价格低于 10元 的菜品的名称 、价格 及其 菜品的分类名称 .内连接 select db04.dish.name '菜名', db04.dish.price '价格',category.name '菜品分类' from dish , category where db04.dish.price<10 and category.id = db04.dish.category_id ; -- 2. 查询所有价格在 10元(含)到50元(含)之间 且 状态为'起售'的菜品名称、价格 及其 菜品的分类名称 (即使菜品没有分类 , 也需要将菜品查询出来). select d.name '菜名',d.price '价格',c.name '菜品分类' from dish d left join category c on d.category_id = c.id where (d.price between 10 and 50 ) and d.status = '1' ; -- 3. 查询每个分类下最贵的菜品, 展示出分类的名称、最贵的菜品的价格 . select c.name '菜品名称',max(d.price) '最贵菜品价格' from category c ,dish d where c.id = d.category_id group by c.name ;
项目连接mysql数据库
- 首先创建一个mysql数据库 驱动要选com.mysql.cj.jdbc.Driver
输入用户名和密码自动点击测试连接如果成功则创建- 在mysql中创建一个架构 假设命名为UserA
- 配置maven中mysql的位置坐标
<dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <scope>runtime</scope> </dependency>
- 在spring-boot的项目配置文件中(application.yml或者application.yaml)中输入数据库连接的四要素
spring: datasource: url: jdbc:mysql://localhost:3306/USerA driver-class-name: com.mysql.cj.jdbc.Driver username: root password: ****
其中url jdbc:mysql://localhost:3306为固定格式 /UserA指定数据库的框架
driver-class-name为刚开始的驱动全类名这样就配置好了