简体   繁体   English

如何避免多次加入同一个表

[英]How to avoid joining the same table multiple times

In the simplified example: The idea is to get all (player, coach, and ref) names into the final query, but the only way I can think to do that is to join 3 times on the respective id.在简化的示例中:想法是将所有(球员、教练和裁判)名称都放入最终查询中,但我能想到的唯一方法是在相应的 id 上加入 3 次。 What is a better way?什么是更好的方法?

Team团队

...|Coachid | Playerid | Refid|
    --------------------------
...|   98    |  23    |  77    |

Name姓名

Id    | Name      |
--------------------
  98  |  Andy     |
  23  |  Charlie  |
SELECT [t].[Id],
       [t].[TeamName],
       [c].[Name] AS CoachName,
       [p].[Name] AS PlayeName,
       [r].[Name] as RefName
FROM Team [t]
JOIN Name [c]
ON c.id = t.Coachid
JOIN Name [p]
ON p.id = t.PlayerId
JOIN Name [r] 
ON r.id = t.RefId

As it has been commented, your approach is the best way to adress your case and should have good performance.正如评论中所说,您的方法是解决您的案例的最佳方法,并且应该具有良好的性能。

Alternatives would include:替代方案包括:

1) A series of correlated subqueries - this is OK because there is just one value to return per relation: 1) 一系列相关的子查询 - 这是可以的,因为每个关系只返回一个值:

SELECT 
    t.Id,
   t.TeamName,
   (SELECT n.Name FROM AS Name n WHERE n.id = t.CoachId) CoachName,
   (SELECT n.Name FROM AS Name n WHERE n.id = t.PlayerId) PlayerName,
   (SELECT n.Name FROM AS Name n WHERE n.id = t.RefId) RefName
FROM Team t 

2) Conditional aggregation - makes the query more cumbersome: 2)条件聚合——使查询更加繁琐:

SELECT 
    t.Id,
    t.TeamName,
    MAX(CASE WHEN n.id = t.CoachId THEN n.Name END) CoachName,
    MAX(CASE WHEN n.id = t.PlayerId THEN n.Name END) PlayerName,
    MAX(CASE WHEN n.id = t.RefId THEN n.Name END) RefName
FROM Team t
INNER JOIN Name n ON n.id IN (t.CoachId, t.PlayerId, t.RefId)
GROUP BY t.Id, t.TeamName

With the way your table is structured, the way you provided is the best way to do it.根据您的表格的结构方式,您提供的方式是最好的方式。

It is odd though, the way you have structured the Team table.但是,您构建 Team 表的方式很奇怪。

You can simplify the whole query just to one join, if you had made your Team table just have the id's of each person, and in your Name table, you would have the id and the role / position of that id.您可以将整个查询简化为一个连接,如果您让 Team 表只包含每个人的 id,并且在您的 Name 表中,您将拥有该 id 的 id 和角色/位置。

I guess this is a good example of how important it is to structure your tables correctly.我想这是正确构建表格的重要性的一个很好的例子。

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

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