关联表SQL语句

时间:2012-04-30 18:32:35

标签: mysql

我有3张桌子

Racer( racerID, racerName)
Race (raceID, raceName)
RaceJoinRacer(raceID, racersID)

我无法找出将检索哪个" racer"的sql语句。参加过#"比赛"。

这是我到目前为止所做的:

SELECT racerName, raceName 
FROM Racer, Race 
JOIN RaceJoinRacer 
    ON RaceJoinRacer.raceID= Race.raceID

3 个答案:

答案 0 :(得分:4)

您正在混合隐式和显式连接语法。不要在FROM子句中使用逗号。相反,使用两个JOIN语句,这意味着MySQL中的INNER JOIN

SELECT
  racerName, 
  raceName 
FROM
  Race 
  JOIN RaceJoinRacer ON RaceJoinRacer.raceID = Race.raceID
  JOIN Racer ON RaceJoinRacer.racersID = Racer.racerID

如果您想邀请Racer表中没有参加任何比赛的参赛者,请在LEFT JOINRacer之间使用RaceJoinRacer代替:

SELECT
  racerName, 
  raceName 
FROM
  Racer
  LEFT JOIN Racer ON RaceJoinRacer.racersID = Racer.racerID
  JOIN RaceJoinRacer ON RaceJoinRacer.raceID = Race.raceID

答案 1 :(得分:1)

SELECT 
   racerName, 
   Race.raceName 
FROM Racer 
   JOIN RaceJoinRacer ON Racer.racerID = RaceJoinRacer.racersID 
   JOIN Race ON Race.RaceID = RaceJoinRacer.RaceID

答案 2 :(得分:0)

SELECT r.racerName, c.raceName 
FROM Racer r
inner join RaceJoinRacer rj ON r.racerID = rj.racerID 
inner join race on c on rj.raceid = c.raceid