mysql多表联合查询

mysql多表联合查询

一、连接查询

内连接查询

内连接(join):从左表取出一条记录,去和右表中所有记录进行匹配,相同的会保留下来。
基本语法:左表 join 右表 on 左表.字段 = 右表.字段

例:
select a.id,a.name,a,sex,b.country,b.city,b.street
from  student a
join  addr b
on  a.addrid=b.addrid;
外连接查询

左连接(left join):以左表为主表
基本语法:from 左表 left join 右表 on 左表.字段 = 右表.字段

左表不管能不能匹配上条件,最终都会被保留;而右表不能匹配的字段不都被置为NULL

例:
select a.id,a.name,a.addrid,b.country,b.city
from student a left join addr b
on a.addrid=b.addrid;

右连接(right join):以右表为主表
基本语法:from 左表 right join 右表 on 左表.字段 = 右表.字段;

例:
select a.id,a.name,a.addrid,b.country,b.city
from student a right join addr b
on a.addrid=b.addrid;

二、联合查询

联合查询结果是将多个select语句的查询结果联合到一起。
可以使用union和union all关键字进行合并。

基本语法:
select 语句1
union [union 选项]
select 语句2
union [union 选项]
select 语句n

其中union选项有两个选项可选:all(表示重复也输出);distinct(去重,完全重复的,默认会去重)
两个表的字段一致即可。

例:
select id,addrid 
from addr 
union all 
select id,addrid 
from student

联合查询的意义
1.查询同一张表,但是需求不同
2.多表查询:多张表的结构完全一样,保存的数据(结构)也是一样的
联合查询order by的使用
在联合查询中:order by只能最后使用一个,需要对查询语句用括号才行。

例:
---(错误)
select * from student where sex="man" order by score
union
select * from student wherre sex="woman" order by score;
这种情况会报错,因为一个句子中不能有两个order by
---(正确但不符合所需)
select * from student where sex="man" 
union
select * from student wherre sex="woman" order by score;
这种情况是正确的,但是合并又没有意义,他会把之前的sex分好的情况给打乱
---(正确)
(select * from student where sex="man" order by score 
limit 10)
union
(select * from student wherre sex="woman" order by score
limit 10);
在子语句中使用order by,由于优先级的问题,需要将整个子句用()括起来,且必须和limit结合使用,否则不会生效。

三、子查询

在SQL查询中嵌套查询称为子查询。但是子查询会对表每一条数据进行查询,所以单表数据过大时不建议使用。
1.带in关键字的子查询
将原表中特定列的值与子查询返回结果中的值比较

例:查询学生成绩大于80的所有信息
select *
from student 
where score in
(select score from student where score>80);

2.带比较运算符的子查询
经常使用的比较运算符有=,<>或!=(不等于),<, <=, >, >=
3.带exists的子查询
exists:用来判断某些条件是否满足(跨表),用在where之后,且返回结果只有0和1

例:如果存在成绩大于90的人则列出整个表
select * 
from student
where exists
(select * from student where score >90);

4.带any关键字的子查询
any关键字表示满足其中的任意一个条件,就执行外边的语句。

例:从addr表中查询addrid,输出student表中addrid小于addr表中最大addrid的行
select *
from student 
where addrid<any
(select addrid 
from addr);

5.带all关键字的子查询
all和any相反,all表示满足所有的结果,才执行外边语句

例:从addr表中查询addrid,输出student表中addrid大于addr表中最大addrid的行
select *
from student 
where addrid>all
(select addrid 
from addr);
posted @ 2022-02-25 19:43  TaoNiの小窝  阅读(629)  评论(0编辑  收藏  举报