安全性好,效率不高: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 多表关联查询、 数据库索引
基础教程推荐
猜你喜欢
- 自己动手用Springboot实现仿百度网盘的实践 2023-08-08
- JSP 开发之Spring Security详解 2023-07-30
- Java ThreadPoolExecutor线程池有关介绍 2023-05-13
- SpringBoot项目使用mybatis-plus代码生成的实例详解 2023-06-11
- GsonFormat快速生成JSon实体类的实现 2023-07-14
- jsp使用ECharts动态在地图上标识点 2023-08-02
- SpringBoot2入门自动配置原理及源码分析 2022-11-23
- Java实现经典游戏打砖块游戏的示例代码 2022-10-31
- Java中泛型的示例详解 2023-06-17
- 详解Java LinkedHashMap与HashMap的使用 2023-06-30
