简体   繁体   English

多次联接同一张桌子

[英]Joining same table multiple times

I have 2 tables Person an Department - where each person has multiple departments registered against him. 我有2个表Person a Department-每个人都有多个针对他注册的部门。

Person

id|name|dept1|dept2|dept3
1 |Jane|100  |102  |106

Dept
id |Name
100|Accounts
...
102|HR
...
106|Admin

Whats the most elegant sql to display Jane's record as follows: 什么是显示Jane记录的最优雅的sql,如下所示:

    Jane|Accounts|HR|Admin

Use this. 用这个。 And work on your naming convention to make all column names unique independent of table. 并按照您的命名约定进行工作,以使所有列名的唯一性与表无关。

SELECT
Person.id, Person.name, dept1.Name, dept2.Name, dept3.Name
LEFT JOIN Dept dept1 ON dept1.id = Person.dept1
LEFT JOIN Dept dept2 ON dept2.id = Person.dept2
LEFT JOIN Dept dept3 ON dept3.id = Person.dept3

Something like this will let you join the same table multiple times. 这样的事情会让您多次连接同一张表。 You just give each join a different alias 您只需为每个联接赋予不同的别名

SELECT * 
FROM Person AS P 
     INNER JOIN Dept AS D1 ON P.dept1 = D1.id 
     INNER JOIN Dept AS D2 ON P.dept2 = D2.id
WHERE P.name = 'Jane'

Ideally you would normalise the data in your Person table and have a linking table between Person and Dept eg PersonDepartmentLinking (or whatever convention you have for linking table naming conventions), assuming you have any control over the schema and it's possible to add the relationship that way. 理想情况下,假设您对架构有任何控制权,并且可以添加以下关系,则可以对Person表中的数据进行规范化,并在Person和Dept之间建立一个链接表,例如PersonDepartmentLinking (或用于链接表命名约定的任何约定)。方式。

You can use STUFF in this case 在这种情况下,您可以使用STUFF

   Select name,
   Stuff((Select distinct ', ' + cast(Name as varchar(20))
           From #Dept t2
           Where t2.Id = t1.Id
           FOR XML PATH('')),1,1,'') 
    From Person t1

The only way that I know is a join for each column. 我知道的唯一方法是每个列的联接。 But if you are in the way of designing the tables, i suggest you to normalize the DB. 但是,如果您要设计表,则建议您标准化数据库。 If a person need an extra dept column, you need to alter the table to add a new property of person. 如果人员需要额外的部门列,则需要更改表以添加人员的新属性。

For me, 3 entities are needed: - Person - Department - person_department_assignation 对我来说,需要3个实体:-人员-部门-person_department_assignation

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

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