安全性好,效率不高:eg: Hashmap--线程不安全,效率高 / Hashtable; TCP--安全但是效率不高 / UDP ### 多表关联查询#### 一对多关系- 嵌套查询```sqlselect * from address where uid = (select id from ...
安全性好,效率不高:eg: Hashmap--线程不安全,效率高 / Hashtable; TCP--安全但是效率不高 / UDP



### 多表关联查询
#### 一对多关系
- 嵌套查询
```sql
select * from address where uid = (select id from user where name = '李四');
```
- 连接查询
- 内连接
```sql
select u.name uname,u.score,a.name aname from user u inner join address a where u.name = "张三" and u.id = a.uid;
```
```sql
select u.name uname,u.score,a.name aname from user u,address a where u.name = "张三" and u.id = a.uid;
```
- 外连接
- 左连接:左表所有数据和右表满足条件的数据
```sql
select * from user u left join address a on u.id = a.uid and u.name = "张三";
```
- 右连接:右表所有数据和左表满足条件的数据
```sql
select * from user u right join address a on u.id = a.uid and u.name = "张三";
```
#### 多对多关系
```sql
create table student(
id int primary key auto_increment,
name varchar(11)
);
create table course(
id int primary key auto_increment,
name varchar(11)
);
```
多对多关系的建立不能直接给两张参与的数据表设置主外键关联关系,需要创建第三张表,来间接促成两张表的多对多关系,中间表中存在两个外键,分别被两张目标表的主键约束,两张目标表都是主表,中间表是两张目标表的从表。
```sql
create table student_course(
id int primary key auto_increment,
sid int,
cid int,
foreign key (sid) references student(id),
foreign key (cid) references course(id)
);
```
嵌套查询
```sql
select * from student_course sc,course c,student s where c.id = sc.cid and s.id = sc.sid and sid = (select id from student where name = "张三");
```
内连接查询
```sql
select s.name sname,c.name cname from student s,course c,student_course sc where s.id = sc.sid and c.id = sc.cid;
```
去重 distinct
```sql
select distinct s.name sname,c.name cname from student s,course c,student_course sc where s.id = sc.sid and c.id = sc.cid;
```
分页 limit index,length
limit 本质上就是在截取查询到的结果集,index 是起始下标,length 是截取的长度。
```sql
select * from user limit 0,10;
```

### 数据库索引 索引是一种特殊的数据库结构,可以用来快速查询数据库表中的特定记录,索引是提高数据库性能的重要方式,所有字段都可以添加索引。 索引包括:普通索引、唯一性索引、全文索引、单列索引、多列索引、空间索引。 使用索引可以提升检索数据的速度,但是创建和维护所以需要耗费大量的时间,索引需要占用大量的物理空间。 普通索引:不需要任何限制条件的索引,可在任意数据类型上创建。 唯一索引:索引的值必须唯一,比如主键索引。 全文索引:只能创建在 char varchar text 类型的字段上,查询数据量较大的字符串类型字段时,使用全文索引可以提高效率,InnoDB 存储引擎不支持全文索引。 单列索引:只对应一个字段的索引。 多列索引:在一张表的多个字段上创建一个索引,查询时使用第一个字段,即可触发索引。 空间索引:只能建立在空间数据类型上(GIS),InnoDB 存储引擎不支持空间索引。
沃梦达教程
本文标题为:69期-Java SE-033_MySQL-4 多表关联查询、 数据库索引
猜你喜欢
- Java数组与二维数组及替换空格实战真题讲解 2023-03-11
- 详解SpringMVC的两种实现方式 2023-06-17
- Java线程生命周期的终止与复位 2023-02-11
- Spring中过滤器(Filter)和拦截器(Interceptor)的区别和联系解析 2023-06-24
- JSP 开发之Servlet解决网页缓存问题 2023-07-30
- selenium4.0版本在springboot中的使用问题的坑 2023-02-28
- springboot中使用mybatisplus自带插件实现分页的示例代码 2023-06-01
- SpringSecurity详解整合JWT实现全过程 2023-03-21
- Spring 容器初始化 register 与 refresh方法 2023-02-19
- Java实战花店商城系统的实现流程 2023-08-10
