0

我正在尝试执行一个简单的 mysql 连接:

我有一个表格,matches其中包含两个我想加入的字段:team1team2.

我想找到存储在teams表中的团队的相应名称:

SELECT teams.team_name AS "name1", teams.team_name AS "name2", matches.id
FROM teams, matches 
WHERE matches.id=1
AND matches.team1_id=teams.team_id
AND matches.team2_id=teams.team_id

如果我删除最后一个和条件中的任何一个,我会得到一个结果,但如果我同时包含两个,我会得到一个空集?

我究竟做错了什么?

4

4 回答 4

3

对于要在查询中唯一引用的每个团队,您需要一个单独的别名,否则 SQL 将比较同一行。

SELECT team1.team_name AS "name1", team2.team_name AS "name2", matches.id
FROM teams team1, teams team2, matches 
WHERE matches.id=1
AND matches.team1_id=team1.team_id
AND matches.team2_id=team2.team_id

在这里,我们现在有 team1 和 team2 的 2 个团队表别名,因此它们每个都可以引用不同的行。

于 2013-04-16T15:21:07.780 回答
2

您需要在表上加入teams两次,matches因为其中两列依赖于它,

SELECT  a.*,                -- <<== select column that you want to project
        b.team_name AS Team1Name,
        c.Team_name AS Team2Name
FROM    matches a
        INNER JOIN teams b
            ON a.team1_ID = b.team_ID
        INNER JOIN teams c
            ON a.team2_ID = c.team_ID
-- WHERE a.id = 1

要进一步了解有关联接的更多信息,请访问以下链接:

于 2013-04-16T15:21:29.227 回答
0

您的查询将仅返回团队与自己比赛的记录(当然这永远不会发生)。您需要针对团队的两个不同联接,因此有两个实例:

select
    teams1.team_name as "name1"
    ,teams2.team_name as "name2"
from
    matches
join
    teams teams1 on matches.team1_id = teams1.team_id
join
    teams teams2 on matches.team2_id = teams2.team_id
where
    matches.id = 1
于 2013-04-16T15:21:48.190 回答
0

尝试这个:

SELECT team1.team_name AS "name1", team2.team_name AS "name2", matches.id
FROM teams as team1, teams as team2, matches 
WHERE matches.id=1
AND matches.team1_id=team1.team_id
AND matches.team2_id=team2.team_id
于 2013-04-16T15:22:01.027 回答