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;">22222111<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,否则SQL将报错,但是s_name这种只在base_worker表中存在的字段则没有这个限制。 b.s_id,e.s_phone extra_worker e b.s_id
返回查询结果集合中的不仅仅包含符合的连接条件的行,而且还包含左表或右表中的所有数据行。外连接分为左外连接和右外连接,这里先看一下左外连接。 左外连接,返回的是左表中的所有记录以及由表中连接字段相等的记录。 b.s_id,e.s_phone extra_worker e b.s_id
将返回右表中的所有行,如果右表中的某行在左表中没有匹配的行,左表将返回空值。 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表中的所有数据都会被查出来。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |