Query

如何從兩個表中檢索兩列的數據?

  • October 31, 2018

我有兩個表 MATCH_MASTER 和 TEAM_MASTER

MATCH_MASTER

|---------------------------|
|M_ID | TEAM1_ID | TEAM2_ID |
|---------------------------|
|  1  |     1    |     2    |

TEAM_MASTER

|T_ID | T_NAME |
|--------------|
|  1  |    A   |
|  2  |    B   |

我想選擇 M_ID、team1 名稱和 team2 名稱。

我的查詢結果應該是這樣的:

|------------------------|
|M_ID | t1_Name | t2Name |
|------------------------|
|  1  |    A    |   B    |

我怎樣才能做到這一點?

嘗試跟隨。

select T1.M_ID, 
   (select T2.T_NAME from TEAM_MASTER as T2 
   where T1.TEAM1_ID = T2.T_ID) as t1_Name,
   (select T2.T_NAME from TEAM_MASTER as T2 
   where T1.TEAM2_ID = T2.T_ID) as t2Name
   from MATCH_MASTER as T1;

該解決方案(雖然較晚)實現了相同的目標,但沒有子選擇,它對於更大的數據集應該執行得更快。

SELECT MM.M_ID
   , TM1.T_NAME AS t1_Name
   , TM2.T_NAME AS t2_Name
FROM MATCH_MASTER AS MM
   INNER JOIN TEAM_MASTER AS TM1 ON TM1.T_ID = MM.TEAM1_ID
   INNER JOIN TEAM_MASTER AS TM2 ON TM2.T_ID = MM.TEAM2_ID

引用自:https://dba.stackexchange.com/questions/72445