INNER JOIN有两列不能正常工作

时间:2014-11-19 17:36:04

标签: mysql

我有两张名为' club'和'时间表'在数据库中。俱乐部的栏目是club_no,俱乐部和体育场。时间表有四列:match_no,team_one,team_two和date。

' Match_no'范围从1到56.' team_one'和' team_two'数字从1到8.这八个数字来自' club_no'表俱乐部中的专栏。

但是当我把这个查询放到零行时:

SELECT * FROM timetable
INNER JOIN clubs ON (
    timetable.team_one=clubs.club_no AND timetable.team_two=clubs.club_no
);

我想要的是一个包含如下列名称的表:Match_no,team_one,team_two和date。但是team_one和team_two这两个专栏应该被来自俱乐部的俱乐部名称所取代。表使用' club_no'这对每个俱乐部来说都是独一无二的。

另外,我在stackoverflow上尝试了几个关于这个主题的答案但没有帮助。它总是返回0行。

5 个答案:

答案 0 :(得分:4)

您无法在一次加入中执行此操作。您的ON子句正在查找 team_oneteam_two等于club_no的行。因此,它等同于team_one=team_two,我假设你没有。{/ p>

您需要做的是为每个团队执行JOIN

SELECT timetable.Match_no, timetable.date, club1.club AS team1, club2.club AS team2
FROM timetable
INNER JOIN clubs AS club1 ON timetable.team_one = club1.club_no
INNER JOIN clubs AS club2 ON timetable.team_two = club2.club_no;

答案 1 :(得分:2)

你试过吗

SELECT C1.club, C2.club, T.Match_no, T.Date FROM timetable T 
INNER JOIN clubs C1 ON C1.club_no = T.team_one
INNER JOIN clubs C2 ON C2.club_no = T.team_two

答案 2 :(得分:1)

我想你想要

select * from timetable
  inner join clubs on (timetable.team_once = clubs.club_no or timetable.team_two=clubs.club_no)

答案 3 :(得分:1)

尝试将AND更改为OR

SELECT * FROM timetable t
JOIN clubs c ON t.team_one=c.club_no OR t.team_two=c.club_no;

或者您也可以加入每个团队,这可能是更好的解决方案

SELECT t.time, c.match_no, c.team_one, c1.team_two
FROM timetable t
JOIN clubs c ON t.team_one=c.club_no
JOIN clubs c1 ON t.team_two=c1.club_no

注意我为您的表添加了别名,因为当您有一个短表名时,它更容易阅读列

答案 4 :(得分:0)

这是使用嵌套连接的一种解决方案。这有效但我觉得它不是最优化的解决方案。

select m_no, team1, clubs.club, date FROM 
    ( select timetable.match_no as m_no, clubs.club as team1, timetable.team_two as team2, timetable.date as date 
       FROM timetable INNER JOIN clubs ON timetable.team_one = clubs.club_no) T 
    INNER JOIN clubs ON T.team2=clubs.club_no