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;
即可得到
以上就是本文的全部內容,希望大家能夠喜歡。