经典mysql连接查询例题
作者:H&K 时间:2024-01-14 17:32:29
MySQL连接查询相信大家都有所了解,连接查询是在数据库查询操作的时候经常用到的,下面就为您介绍MySQL连接查询
mysql连接查询:支持多表连接
对同一张表可以重复连接多次(别名在多次连接同一张表时很重要)
例题1:
下面有2张表
teams表
比赛结果表:result
问题:
得出一张表:主队,客队,比赛成绩,比赛时间
方法一:子查询和连接查询混合
step1:
select result.id, t_name as h_name,match_time,result from teams join result on teams.t_id=result.h_id
step2:
select result.id ,t_name as g_name from teams join result on teams.t_id=result.g_id
得到
step3:根据比赛的id 相等连接以上两表即可
select t1.id,h_name,g_name,result,match_time from
(select result.id, t_name as h_name,match_time,result from teams join result on teams.t_id=result.h_id) as t1
join
(select result.id ,t_name as g_name from teams join result on teams.t_id=result.g_id) as t2
on t1.id=t2.id;
即可得到
结果是出来了,有点繁琐
方法二:多次连接查询
select result.id,t1.t_name as h_name ,t2.t_name as g_name ,result,match_time from result
join
teams as t1 on result.h_id=t1.t_id
join
teams as t2 on t2.t_id=result.g_id;
即可得到:
Teams表要连接2次所以要有别名
例题2:
现有下表 subject
求这样一个表
父栏目名 ,子栏目名称
连接查询
自己连接自己更需要别名了
select t1.name as p_name,t2.name as son_name from subject as t1 join subject as t2 on t1.id=t2.pid;
即可得到
标签:mysql,连接查询
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
mysql复制中临时表的运用技巧
2024-01-20 10:51:49
MySQL全局共享内存介绍
2024-01-14 09:40:14
ASP使用wsImage组件给图片加水印代码
2010-06-09 19:23:00
Window 7/XP 安装Apache 2.4与PHP 5.4 的过程详解
2023-11-24 09:28:09
Python进阶:生成器 懒人版本的迭代器详解
2021-12-21 16:08:05
如何利用Matplotlib库绘制动画及保存GIF图片
2021-06-08 17:15:40
![](https://img.aspxhome.com/file/2023/7/81677_0s.gif)
.NET反向代理组件YARP介绍
2023-07-23 02:29:45
![](https://img.aspxhome.com/file/2023/8/78088_0s.png)
JS onmousemove鼠标移动坐标接龙DIV效果实例
2023-08-08 19:59:13
![](https://img.aspxhome.com/file/2023/0/56030_0s.gif)
利用ctypes提高Python的执行速度
2023-11-04 22:33:55
教你怎么用python连接sql server
2023-01-31 22:27:33
![](https://img.aspxhome.com/file/2023/2/124642_0s.png)
Python多进程fork()函数详解
2023-06-08 19:41:37
Javascript的时间戳和php的时间戳转换注意事项
2023-11-19 16:12:30
如何利用pygame实现简单的五子棋游戏
2023-04-12 17:48:03
![](https://img.aspxhome.com/file/2023/8/121018_0s.jpg)
php实现xml与json之间的相互转换功能实例
2023-11-22 05:38:00
从Web查询数据库之PHP与MySQL篇
2009-09-19 16:58:00
自学MySql内置函数知识点总结
2024-01-23 11:19:04
安装MySQL5.0后出现1607异常的解决办法
2009-02-26 15:52:00
浅析vue中的nextTick
2024-04-26 17:42:21
![](https://img.aspxhome.com/file/2023/9/133119_0s.png)
MySQL七大JOIN的具体使用
2024-01-28 04:11:31
![](https://img.aspxhome.com/file/2023/8/80138_0s.png)
如何删除Git本地仓库和删除GitHub上的Git远程仓库Repository(推荐)
2023-01-30 16:07:59
![](https://img.aspxhome.com/file/2023/7/130897_0s.png)