2

I have a simple table schema:

Person: ID, Name
PhoneNumber: ID, Type, Number                    #Type can be 'home' or 'mobile'.
PersonPhoneNumber: ID, Person_ID, PhoneNumber_ID #A join table that connects the
                                                 #person to a phone number.

As data I have:

Person: 1, "Ed"
PhoneNumber: 1, "home", 1111
PhoneNumber: 2, "mobile", 2222
PersonPhoneNumber: 1, 1 /*(Person_ID)*/, 1 /*(PhoneNumber_ID*/
PersonPhoneNumber: 2, 1 /*(Person_ID)*/, 2 /*(PhoneNumber_ID*/

I want to write a view that returns:

Name    |Home    |Mobile
-----------------------------
"Ed"     1111     2222
"Joe"    3333     4444
... etc

Any tips on how I approach this?

Note: These tables are a snippet from a larger schema which explains why its a many to many and not more simplistic.

4

4 回答 4

1

如果您有多个号码或者可能不止家庭/手机号码,您可以以更复杂的方式执行此操作,但现在,如果您只有两个号码,那么这将起作用:

SELECT Name, HomeNumber.Number AS Home, MobileNumber.Number AS Mobile
FROM Person
    LEFT JOIN PersonPhoneNumber HomeMap
        ON Person.ID = HomeMap.Person_ID
    LEFT JOIN PhoneNumber HomeNumber
        ON HomeMap.PhoneNumber_ID = HomeNumber.ID AND HomeNumber.Type = 'home'
    LEFT JOIN PersonPhoneNumber MobileMap
        ON Person.ID = MobileMap.Person_ID
    LEFT JOIN PhoneNumber MobileNumber
        ON MobileMap.PhoneNumber_ID = MobileNumber.ID AND MobileNumber.Type = 'mobile'

顺便说一句,如果您不想要任何数字的人,那么您可以将PersonPhoneNumber映射设置为 aJOIN而不是 aLEFT JOIN

于 2012-04-17T17:49:57.173 回答
0
select  p.Name
,       pnh.Number as Home
,       pnm.Number as Mobile
from    Person p
left join 
        PersonPhoneNumber pn
on      pn.Person_ID = p.ID
left join    
        PhoneNumber pnh
on      pnh.ID = pn.PhoneNumber_ID
        and phh.Type = 'home'
left join    
        PhoneNumber pnm
on      pnm.ID = pn.PhoneNumber_ID
        and pnm.Type = 'mobile'
于 2012-04-17T17:50:14.553 回答
0

这将帮助你

select * from @Person p
left join @PersonPhoneNumber ppn
on p.ID = ppn.PersonID
right join @PhoneNumber pn
on ppn.PhoneNoID = pn.ID
于 2012-04-18T13:20:00.413 回答
0

希望这可以帮助


SELECT DISTINCT P.NAME,
                (SELECT DISTINCT PN1.PH_NUMBER
                   FROM PHONE_NUMBER PN1
                  WHERE PN1.ID = PN.ID
                    AND PN1.TYPE = 'Home') AS HOME,
                (SELECT DISTINCT PN1.PH_NUMBER
                   FROM PHONE_NUMBER PN1
                  WHERE PN1.ID = PN.ID
                    AND PN1.TYPE = 'Mobile') AS MOBILE
  FROM PERSON P, PHONE_NUMBER PN
  ORDER BY P.NAME

于 2012-04-18T04:12:09.670 回答