网络编程
位置:首页>> 网络编程>> 数据库>> MySQL多表连接查询详解

MySQL多表连接查询详解

作者:开到荼蘼223's  发布时间:2024-01-27 13:07:57 

标签:MySQL,多表连接,查询

多表连接查询

表与表之间的连接分为内连接和外连接

  • 内连接:仅选出两张表互相匹配的记录

  • 外连接:既包括两张表匹配的记录,也包括不匹配的记录,同时外连接又分为左外连接(左连接)和右外连接(右连接)

内连接

首先准备两张表

学生student表

MySQL多表连接查询详解

分数score表

MySQL多表连接查询详解

内连接:在每个表中找出符合条件的共有记录
查询student表中的学生姓名和分数

第一种写法:只使用where


select a.s_name, b.s_score from student a,score b where a.s_id = b.s_id;

第二种写法:join … on…


select a.s_name, b.s_score from student a join score b on a.s_id = b.s_id

第三种写法:inner join … on…


select a.s_name, b.s_score from student a inner join score b on a.s_id = b.s_id

MySQL多表连接查询详解

左连接

左连接:根据左表的记录,在被连接的右表中找出符合条件的记录与之匹配,如果找不到与左表匹配的,用null表示

第一种写法:left join … on …


select a.s_name,b.s_score from student a left join score b on a.s_id = b.s_id

第二种写法:left outer join … on …


select a.s_name,b.s_score from student a left outer join score b on a.s_id = b.s_id

MySQL多表连接查询详解

右连接

**右连接:**根据右表的记录,在被连接的左表中找出符合条件的记录与之匹配,如果找不到匹配的,用null表示

第一种写法:right join … on …


select a.s_name,b.s_score from student a right join score b on a.s_id = b.s_id;

第二种写法:right outer join … on …


select a.s_name,b.s_score from student a right outer join score b on a.s_id = b.s_id;

MySQL多表连接查询详解

子查询

子查询:是多表连接查询的一种实现方式,在一个select语句的from子句或where子句中嵌套了另一个select语句,外层的select查询语句成为主查询,换句话将就是WHERE或FORM中的查询语句称为子查询

WHERE子句中的子查询:子查询返回的值作为主查询的查询条件

FROM子句中的子查询:子查询返回的是一张虚拟的表,主查询从该查询从临时表查询出满足的条件

来源:https://blog.csdn.net/m0_56649557/article/details/119547080

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com