Friday, March 23, 2012

Mental Block on SQL query. Joining one to many with one of the many

Sorry for the akward title, not sure how to say this. I have a Person table and a addresses table. Each person may have many address records as shown below:

Person

--

PersonID | AutoNum

fName | varchar

lName | varchar

...etc

Addresses

addressID | AutoNum

personID | int (FK)

address1 | varchar

city | varchar

state | varchar

isPrimary | bit

...etc

What I'm trying to do is select all from Person and the city and state of each person's primary address. A little voice keeps saying subquery...but I can't figure it out. So far I have the SQL below, but if there is no address or no address where isPrimary = 1, it fails to return the person record. I need the person record regardless of if they have a primary address. Does that make sense?

Doesn't return all Person records:

SELECT Person.*, Address.City, Address.State

FROM Person LEFT OUTER JOIN Address

ON Person.PersonID = Address.PersonID
WHERE (Address.isPrimary= 1)
ORDER BY Person.lName, Person.fName

Try:

Code Snippet

SELECT Person.*, Address.City, Address.State, Address.isPrimary

FROM Person LEFT OUTER JOIN Address

ON Person.PersonID = Address.PersonID
AND (Address.isPrimary= 1)
ORDER BY Person.lName, Person.fName

|||Perfect, thank you.

No comments:

Post a Comment