SQL选择两个与另一个表有关系的表

时间:2012-06-27 09:34:54

标签: mysql sql

我想创建一个查询,从下表中选择列PlayerName,PlayerNumber,Location,PartnerName,PartnerNumber,Location:

  • 玩家(列:Id,PlayerName,PlayerNumber,LocationId)
  • 合作伙伴(列:ID,PartnerName,PartnerNumber,LocationId)
  • 地点(列:ID,位置)

但我无法弄清楚如何做到这一点。有没有人有任何想法?

5 个答案:

答案 0 :(得分:2)

在考虑注册表后找到更新的查询。

SELECT players.playername, 
       player.playernumber, 
       L1.location, 
       partners.partnername, 
       partners.partnernumber, 
       L2.location 
FROM   registration R 
       INNER JOIN players 
               ON players.id = R.playerid 
       INNER JOIN partners 
               ON partners.id = R.partnerid 
       INNER JOIN locations L1 
               ON players.locationid = L1.id 
       INNER JOIN locations L2 
               ON partners.locationid = L2.id 

答案 1 :(得分:1)

简单直接

select PL.PlayerName , PL.PlayerNumber, L.Location, PT.PartnerName, PT.PartnerNumber
from  Players PL, Location L, Patners PT
where L.id = PL.LocationId and L.id = P.LocationId

这也可以使用UNION来完成,但对此不太确定

答案 2 :(得分:1)

试试这个..我不确定

select pl.Id,pl.PlayerName,pl.PlayerNumber,pa.ID,pa.PartnerName,pa.PartnerNumber,l.Location 
from Players as  pl,Partners as pa ,Location as l 
where pl.LocationId = pa.LocationId and l.LocationId = pl.LocationId
and pa.LocationId = l.LocationId
AND l.LocationId = <some id>

答案 3 :(得分:0)

Select PlayerName , PlayerNumber, Location, PartnerName, PartnerNumber
from Players pl
inner join Partners pa on pl.LocationId=pa.LocationId
inner join Location L on L.id=pa.LocationId
where Location = 'String to search for'

答案 4 :(得分:0)

select
  PlayerName,
  PlayerNumber,
  Location,
  PartnerName,
  PartnerNumber
from players
  left join locations
    on locations.id = players.LocationId
  left join partners
    on partners.LocationId = locations.id