我正在尝试执行一个简单的mysql连接:
我有matches
的表格,其中包含两个我要加入的字段:team1
和team2
。
我想找到存储在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
如果我删除了最后一个和条件我得到了一个结果,但如果我同时包括两个我得到一个空集?
我做错了什么?
答案 0 :(得分: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个team表的别名,因此他们可以分别引用不同的行。
答案 1 :(得分: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
要进一步了解联接,请访问以下链接:
答案 2 :(得分: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
答案 3 :(得分: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