2013-07-15 80 views
0

我有三個表:MySQL查詢聯接三個表

players 
------ 
id|name 

teams 
------- 
id|name 

teams_players 
------------- 
id|teamID|playerID 

我現在想從表「玩家」,其中players.id例如在球隊ID爲15.換句話說每個條目:我想讓每個屬於特定球隊的球員(例如teamID = 15)

我嘗試了一個加入但是失敗了。

這是我走到這一步:

 "SELECT players.* 
     FROM players 
     JOIN teams_players 
     ON teams_players.teamID = 15 
     GROUP BY players.id"; 

回答

2

你的方式過於複雜這一點。

select players.* 
from players 
join teams_players 
on players.id = teams_players.playerid 
where teams_players.teamid = 15 

JOIN部分無關編號爲15。15,你是如何篩選結果。

+0

OMG這麼簡單!謝謝 :) –

0

你可以加入一個以上的條件,你的表還你沒有提到你的表之間的關係on子句中

SELECT players.* 
     FROM players 
     JOIN teams_players 
     ON (players.id = teams_players.playerid AND teams_players.teamID = 15) 
     GROUP BY players.id