簡體   English   中英

SQL查詢幫助-多個聯接

[英]SQL Query Help - Multiple JOINS

對該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的名稱?

將第二個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;

您可以通過將表連接在一起來做到這一點。 訣竅是您必須兩次包含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;

我還為其他表添加了表別名,這使查詢更易於閱讀。

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)

您需要使用Player2ID字段上的Players表再次加入查詢。 因此,將查詢更改為:

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