簡體   English   中英

如何將一列連接到另一個表中的所有列

[英]how to join one column to all columns from another table

我有兩張桌子,球員和陣容表與團隊中的所有球員

陣容表有這個列

 `match_id`, `goalkeeper`, `center_back`, `center_back_2`, `right_outside_back`, `left_outside_back`, `defensive_center_midfielder`, `center_midfielder`, `attacking_center_midfielder`, `right_winger`, `left_winger`, `center_forward`

並且所有列都具有玩家表中一名玩家的 ID

如何將這里的所有列加入到玩家表中?

與此相符的東西:

select match_id, 
gk.player_name as goalkeeper, 
c_back.player_name as center_back 
from matches
left join players as gk on gk.id = matches.goalkeeper
left join players as c_back on c_back.id = matches.center_back
...
where match_id = x

基本上很多left_joins。

如果您重新設計數據庫模型並添加包含以下列的表:match_id、position_id、player_id 事情會簡單得多,數據庫引擎將感謝您。

那么你的 SQL 看起來會簡單得多:

select positions.* from position_definition as positions
left join (select mp.*, players.player_name from  match_players as mp left join players on mp.player_id = players.id where match_id = x) 
as team on team.position_id = positions.id

(類似的東西,這里沒有檢查准確性)還添加了一個額外的表格,其中包含一場比賽中所有位置的列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM