此SQL查询出现问题。情况如下:
我有三个表格结构如下:
Events -> fields ID and Name,
Players -> fields ID and Name,
Matches -> fields ID, EventID, Player1ID, Player2ID
我想执行一个向我显示匹配表的查询,但将EventID替换为Event.Name,将Player1ID替换为Players.Name,将Player2ID替换为Players.Name。
我很容易使用这个获得一个玩家和事件:
SELECT
Players.Name as Player1, Events.Name
FROM
(Matches
INNER JOIN
Events ON (Matches.EventID=Events.ID))
INNER JOIN
Players ON (Matches.Player1ID = Player.ID) ;
但是,我如何获得Player2的名字?
答案 0 :(得分:5)
向Players
表添加第二个JOIN:
SELECT
Players.Name as Player1, Events.Name,
p2.Name as Player2
FROM
Matches
INNER JOIN
Events ON Matches.EventID = Events.ID
INNER JOIN
Players ON Matches.Player1ID = Player.ID
INNER JOIN
Players p2 ON Matches.Player2ID = p2.ID;
答案 1 :(得分:1)
您可以通过将表连接在一起来完成此操作。诀窍是你必须两次包含Players
表。在这种情况下,您需要表别名来区分from
子句中对表的这两个引用:
select m.matchid, e.name as event_name, p1.name as player1_name, p2.name as player2_name
from matches m join
events e
on m.eventid = e.id join
players p1
on m.player1 = p1.id join
players p2
on m.player2 = p2.id;
我还为其他表添加了表别名,这使查询更容易阅读。
答案 2 :(得分:0)
SELECT p1.Name, p2.Name, Events.Name
FROM Matches
INNER JOIN Events ON (Matches.EventID=Events.ID))
INNER JOIN Players p1 ON (Matches.Player1ID = p1.ID)
INNER JOIN Players p2 ON (Matches.Player2ID = p2.ID)
答案 3 :(得分:0)
您需要再次使用Players
字段上的Player2ID
表加入查询。因此,请将您的查询更改为:
SELECT one.Name as Player1, two.Name as Player2, Events.Name
FROM
Matches INNER JOIN
Events ON Matches.EventID=Events.ID INNER JOIN
Players one ON Matches.Player1ID = one.ID INNER JOIN
Players two ON Matches.Player1ID = two.ID