MySQL加入奇怪的结果

时间:2013-04-17 13:09:39

标签: mysql join

任何人都可以帮忙,我认为mysql超出了我的想法!

我有以下表格:

  • 匹配
  • 竞争

匹配包含两支球队之间的比赛细节以及相应的比赛。

我想查询特定比赛的所有比赛/赛程的数据库,我想回复:

  • 团队名称
  • 团队ID
  • 团队比赛

这是我的问题:

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

我做错了什么,我检查了数据库,并为每个夹具正确存储了匹配。

感谢。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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