我有一个包含表schedule
和表teams
的数据库(如下图所示)我试图在内部使用homeID
和awayID
schedule
表可以在teams
表上进行联接。...问题是它返回NULL
数据库布局
Schedule
表格布局
teams
表格布局
我的查询
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';
返回结果
有人知道为什么我要为联接获取NULL值吗?我在这里想念什么?任何帮助表示赞赏。
答案 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
是一个整数,因此比较应该是数字,而不是字符串。
我注意到homeId
和visitorId
的字词不匹配teams.teamId
,但是命名表明这是正确的条件。如果正确定义了外键,则类型必须匹配。