1

我有 3 张桌子

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

我无法弄清楚将检索哪个“赛车手”参加了哪个“比赛”的 sql 语句。

这是我到目前为止所拥有的:

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

3 回答 3

4

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

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

如果您想包括Racer未参加任何比赛的表中的赛车手,请使用LEFT JOINbetweenRacerRaceJoinRacer代替:

SELECT
  racerName, 
  raceName 
FROM
  Racer
  LEFT JOIN Racer ON RaceJoinRacer.racersID = Racer.racerID
  JOIN RaceJoinRacer ON RaceJoinRacer.raceID = Race.raceID
于 2012-04-30T18:35:23.020 回答
1
SELECT 
   racerName, 
   Race.raceName 
FROM Racer 
   JOIN RaceJoinRacer ON Racer.racerID = RaceJoinRacer.racersID 
   JOIN Race ON Race.RaceID = RaceJoinRacer.RaceID
于 2012-04-30T18:35:42.337 回答
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
于 2012-04-30T18:35:59.933 回答