2

Suppose I have two SQL tables: Customers and PhoneNumbers.

Suppose that Customers has the following columns: customerId (primary key), fName, lName.

Suppose that PhoneNumbers has the following columns: phoneNumberId (primary key), phoneNumber, customerId (foreign key).

What I understand so far is that if each customer has one phone number, I can select the fName, lName, and phoneNumber of each customer with the following SQL:

SELECT 
    customer.fName, customer.lName, phone.phoneNumber 
FROM 
    Customers customer 
        INNER JOIN phoneNumbers phone ON 
            customer.customerId = phone.customerId

What if a customer may have more than one phone number? How do I get a list of customers with the list of phone numbers of each customer?

My programming language to drive the SQL is C#/.NET.

2
  • @casperOne, thanks for formatting my code :-) Commented Dec 9, 2010 at 14:54
  • logiclabz.com/sql-server/… Commented Dec 9, 2010 at 14:54

4 Answers 4

4

As you say, if there is exactly one PhoneNumber per customer, your query will work.

Customers with more than one Phone Number will also be returned, but the customer record will be duplicated for each different phone number.

The other condition you need to consider is customers with no phone numbers. If you INNER JOIN the tables, then these customers will be excluded from the result set. To include such customers, you need to use an OUTER JOIN.

Sign up to request clarification or add additional context in comments.

Comments

2

The query you've given will return multiple phone numbers if they exist. You'll see rows with customer.fName and customer.lName repeated, each with a different phone.phoneNumber.

Comments

0

You can do the exact same thing. The query you currently list should retrieve the exact results you want; one row per phone number per customer.

Comments

0

You'll get several rows for one customer if it has several numbers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.