0

I have to tables

Customer

CustomerID   Name        Surname
---------------------------------
  1          Adam        Test
  2          Robert      Test2
  3          John        Test3

CustomerAddress

CustomerAddressId  CustomerId     AddressId
-------------------------------------------
1                  1              1
2                  1              2
3                  1              3
4                  2              6
5                  2              7
6                  2              8

I want to select CustomerId from these two tables.

I wrote this query but it multiplies my records.

2
  • 1
    What query did you write? It would be helpful for us to have the query, expected output, etc. Commented Nov 15, 2018 at 15:53
  • you have 2 proposed answers below check them out and either will get you the non multiplied answers your looking for. @adamek339 Commented Nov 15, 2018 at 18:39

3 Answers 3

2

If you're looking for a distinct list of CustomerId from both tables, it'll be easiest to use UNION:

SELECT CustomerId
FROM Customer
UNION SELECT CustomerId
FROM CustomerAddress

Using UNION ALL would show duplicates in your result set.

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

Comments

1

You can use DISTINCT keyword with JOIN :

SELECT DISTINCT C.CustomerId     
FROM Customer c INNER JOIIN
     CustomerAddress cs
     ON CD.CustomerId = C.CustomerId;

Without DISTINCT it would return multiple CustomerIds as because of second table has multiple address for same customer.

Comments

1

If you want to capture Customers which has addresses you can use following script :

SELECT * 
FROM Customer C
WHERE EXISTS (SELECT 1 FROM CustomerAddress CA WHERE C.CustomerId=CA.CustomerId)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.