1

谁能帮忙,我认为mysql超出了我的范围!

我有以下表格:

  • 火柴
  • 团队
  • 竞赛

比赛保存了两支球队之间的比赛的细节和相应的比赛。

我想查询给定比赛的所有游戏/装置的数据库,我想返回:

  • 队名
  • 团队编号
  • 团体赛

这是我的查询:

SELECT
  matches.match_id,
  teamsh.team_name AS "homeTeam",
  teamsa.team_name AS "awayTeam",
  competition.competition_id,
  competition.name
FROM
  matches, teams teamsh, teams teamsa, competition
WHERE
  matches.home_team_id = teamsh.team_id
AND matches.away_team_id = teamsa.team_id
AND matches.competition_id=2

由于某种原因,此查询正确返回了比赛 2 的所有灯具,但它也返回了灯具的行,但也作为比赛 1。我不明白为什么,因为我有这个条款:

AND matches.competition_id=2

我做错了什么,我检查了数据库,并且每个灯具的匹配都正确存储。

谢谢。

4

2 回答 2

3

您尚未明确链接到比赛表(因此它正在执行笛卡尔连接) - 尝试添加:

and matches.competition_id = competition.competition_id

- 到您的查询结束。

虽然,我建议重写查询以使用显式连接语法 - 如下所示:

SELECT m.match_id,
       h.team_name AS "homeTeam",
       a.team_name AS "awayTeam",
       c.competition_id,
       c.name
FROM matches m
JOIN teams h ON m.home_team_id = h.team_id
JOIN teams a ON m.away_team_id = a.team_id
JOIN competition c ON m.competition_id = c.competition_id
WHERE m.competition_id=2
于 2013-04-17T13:15:54.823 回答
1

您忘记了JOIN比赛和比赛表之间的条件。

WHERE
  matches.home_team_id = teamsh.team_id
  AND matches.away_team_id = teamsa.team_id
  AND matches.competition_id = competition.competition_id
  AND matches.competition_id=2
于 2013-04-17T13:15:16.540 回答