MySQL8:连接查询

前端之家收集整理的这篇文章主要介绍了MySQL8:连接查询前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

查询

连接是关系型数据库模型的主要特点。

连接查询是关系型数据库中最主要的查询,主要包括内连接外连接等通过联结运算符可以实现多个表查询

在关系型数据库管理系统中,表建立时各种数据之间的关系不必确定,常把一个实体的所有信息存放在一个表中,当查询数据时通过连接操作查询出存放在多个表中的不同实体信息,当两个或多个表中存在相同意义的字段时,便可以通过这些字段对不同的表进行连接查询

本文将介绍多表之间的内连接查询、外连接查询

( innodb,charset<span style="color: #0000ff;">insert <span style="color: #0000ff;">into base_worker <span style="color: #0000ff;">values(<span style="color: #0000ff;">null,"aaa",<span style="color: #800000; font-weight: bold;">20<span style="color: #000000;">);
<span style="color: #0000ff;">insert
<span style="color: #0000ff;">into
base_worker <span style="color: #0000ff;">values
(<span style="color: #0000ff;">null
,"bbb",<span style="color: #800000; font-weight: bold;">21
<span style="color: #000000;">);
<span style="color: #0000ff;">insert
<span style="color: #0000ff;">into
base_worker <span style="color: #0000ff;">values
(<span style="color: #0000ff;">null,"ccc",<span style="color: #800000; font-weight: bold;">22<span style="color: #000000;">);
<span style="color: #0000ff;">commit;

(( innodb,charset<span style="color: #0000ff;">insert <span style="color: #0000ff;">into extra_worker <span style="color: #0000ff;">values(<span style="color: #0000ff;">null,<span style="color: #800000; font-weight: bold;">1,"中国","<span style="color: #800000; font-weight: bold;">00000000<span style="color: #000000;">");
<span style="color: #0000ff;">insert
<span style="color: #0000ff;">into
extra_worker <span style="color: #0000ff;">values
(<span style="color: #0000ff;">null
,<span style="color: #800000; font-weight: bold;">2
,"美国","<span style="color: #800000; font-weight: bold;">11111111
<span style="color: #000000;">");
<span style="color: #0000ff;">insert
<span style="color: #0000ff;">into
extra_worker <span style="color: #0000ff;">values
(<span style="color: #0000ff;">null
,<span style="color: #800000; font-weight: bold;">5,"英国","<span style="color: #800000; font-weight: bold;">22222222<span style="color: #000000;">");
<span style="color: #0000ff;">commit;

在内连接查询中,只有满足条件的记录才能出现在结果关系中

b.s_id,b.s_name,b.s_age,e.s_nation,e.s_phone b.s_id

查询结果:

查询出来只有两条记录,因为只有这两条记录可以通过s_id相匹配上。

s_id这种在两张表中都存在的字段,必须指明读取的是哪张表中的s_id,否则sql将报错,但是s_name这种只在base_worker表中存在的字段则没有这个限制

sql是内连接最常用的sql写法,内连接还有另外一种sql写法,结果也是一样的:

b.s_id,e.s_phone extra_worker e b.s_id

查询将查询多个表中相关联的行,内连接时返回查询结果集合中的仅仅是符合查询条件和连接条件的行。但有时候需要包含没有关联的行中的数据,即返回查询结果集合中的不仅仅包含符合的连接条件的行,而且还包含左表或右表中的所有数据行。外连接分为左外连接和右外连接,这里先看一下左外连接。

左外连接,返回的是左表中的所有记录以及由表中连接字段相等的记录

sql:

b.s_id,e.s_phone extra_worker e b.s_id

查询结果:

显示了三条纪录,s_id为3的记录在extra_worker表中并没有s_nation与s_phone,所以这两个值为null,但因为base_worker为左表,因此base_worker中的所有数据都会被查出来。

将返回右表中的所有行,如果右表中的某行在左表中没有匹配的行,左表将返回空值。

sql:

e.s_id,e.s_phone extra_worker e b.s_id

查询结果:

同样的,看到显示了三条纪录,s_id为5的记录在base_worker中并没有s_name与s_age,所以这两个值为null,但因为extra_worker表为右表,因此extra_worker表中的所有数据都会被查出来。

猜你在找的MySQL相关文章