SQL左联接返回NULL值

时间:2018-08-30 02:19:43

标签: mysql sql join

我有一个包含表schedule和表teams的数据库(如下图所示)我试图在内部使用homeIDawayID schedule表可以在teams表上进行联接。...问题是它返回NULL

数据库布局

enter image description here

Schedule表格布局

enter image description here

teams表格布局

enter image description here

我的查询

SELECT s.*,
  t1.teamId as homeId_teamId,
  t1.teamCode as homeId_teamCode,
  t1.teamName as homeId_teamName,
  t2.teamId as visitorId_teamId,
  t2.teamCode as visitorId_teamCode,
  t2.teamName as visitorId_teamName
FROM schedule s
  LEFT JOIN teams t1 ON s.homeId = t1.teamName
  LEFT JOIN teams t2 ON s.visitorId = t2.teamName
WHERE  gameID = '1';

返回结果

enter image description here

有人知道为什么我要为联接获取NULL值吗?我在这里想念什么?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

id应该和id(不是名字)一起加入:

SELECT s.*,
      t1.teamId as homeId_teamId,
      t1.teamCode as homeId_teamCode,
      t1.teamName as homeId_teamName,
      t2.teamId as visitorId_teamId,
      t2.teamCode as visitorId_teamCode,
      t2.teamName as visitorId_teamName
FROM schedule s LEFT JOIN
     teams t1
     ON s.homeId = t1.teamId LEFT JOIN
     teams t2
     ON s.visitorId = t2.teamId
WHERE s.gameID = 1;

gameID是一个整数,因此比较应该是数字,而不是字符串。

我注意到homeIdvisitorId的字词不匹配teams.teamId,但是命名表明这是正确的条件。如果正确定义了外键,则类型必须匹配。