简体   繁体   中英

Joining same table multiple times

I have 2 tables Person an Department - where each person has multiple departments registered against him.

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|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.

You can use STUFF in this case

   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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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