简体   繁体   English

SQL查询帮助-多个联接

[英]SQL Query Help - Multiple JOINS

having trouble with this SQL query. 对该SQL查询有麻烦。 Here's the situation: 情况如下:

I have three tables structured as follows: 我有三个表,其结构如下:

Events -> fields ID and Name, 
Players -> fields ID and Name, 
Matches -> fields ID, EventID, Player1ID, Player2ID

I would like to perform a query that shows me the Matches Table, but replaces the EventID with the Event.Name, the Player1ID with the Players.Name and the Player2ID with the Players.Name. 我想执行一个查询,向我显示匹配表,但将EventID替换为Event.Name,将Player1ID替换为Players.Name,将Player2ID替换为Players.Name。

It is easy for me to get one Player and the Event using this: 我很容易使用以下方法获得一名球员和赛事:

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) ;

But, how do I get the Player2's name? 但是,如何获得Player2的名称?

Add a second JOIN to the Players table: 将第二个JOIN添加到Players表中:

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;

You can do this by joining the tables together. 您可以通过将表连接在一起来做到这一点。 The trick is that you have to include the Players table twice. 诀窍是您必须两次包含Players表。 This is a case where you need table aliases to distinguish between these two references to the table in the from clause: 在这种情况下,您需要使用表别名来区分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;

I also added table aliases for the other tables, which makes the query easier to read. 我还为其他表添加了表别名,这使查询更易于阅读。

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)

You need to join the query again with the Players table on the Player2ID field. 您需要使用Player2ID字段上的Players表再次加入查询。 So change your query to: 因此,将查询更改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM