2-04:左右内连接查询与union

左右内连接查询与union

内连接查询:

>select table1.name,table2.name from table1 inner join table2 on table1.name = table2.name;

左连接查询:

>select table1.name,table2.name from table1 left join table2 on table1.name = table2.name;

右连接查询:

>select table1.name,table2.name from table1 right join select2 on table1.name = table2.name;

内连接查询,在on后面的条件不成立的时候,是不返回数据的;
左右连接查询,在on后面的条件不成立的时候,依然返回数据,值为null,例如上面的查询语句,table1表中若没有某个名字与table2表中的名字相同,则还是会返回字段,而left 和 right 就是区分当前查询的表,那张表为主导,left 的时候,table1表中没有查到相等的名字时依然将所有行列出,而与之对应的table2的名字则为NULL;

多张表连接查询:

select
table1.name,table2.name,table3.name
from
table1
inner join
table2
on
table1.id = table2.id
join
table3 on table1.id = table3.id
;

union 合并多条查询结果集

示例:

select * from 表1
union
select * from 表2;

最后返回的结果将是两张表的所有数据的集合
union语句满足的条件是:每个select语句取出的列数必须相同,列名不一定相同,列名称使用第一条select语句的列名称;
union语句,在上述例子中,表1和表2中分别有一行数据完全相同,则会被合并,类似于并集;

union操作合并,耗时,消耗服务器资源,造成浪费;
union all 操作在合并时,不去比较每一行是否一致,则会提升合并的性能;

练习:将两表中id相同的num相加

testa:
+----+-----+
| id | num |
+----+-----+
|  1 |  10 |
|  2 |  20 |
|  3 |  30 |
|  4 |  40 |
|  5 |  50 |
|  6 |  60 |
+----+-----+


testb:
+----+-----+
| id | num |
+----+-----+
|  1 |  20 |
|  2 |  23 |
|  3 | 234 |
|  4 | 234 |
|  5 |  35 |
|  6 |  45 |
+----+-----+

SQL:
select id,sum(num) from 
(
select * from testa
union 
select * from testb
)
as tmp
group by id;

猜你喜欢

转载自blog.csdn.net/a2522086223/article/details/81779512
今日推荐