I am using the AdvetureWorks database. Here is what I would like to do:
Give me the Last Name, First Name, company name and list me all the addresses for customer Virginia Miller, include address type, address, city and state.
You need to join 3 tables together and filter the results. You should only get 2 rows.
This is what I have so far…
Select
SalesLT.Customer.LastName,
SalesLT.Customer.FirstName,
SalesLT.Customer.CompanyName,
CustomerAddress.AddressType,
SalesLT.Address.AddressLine1,
SalesLT.Address.City,
SalesLT.Address.StateProvince
From SalesLT.Customer C, SalesLT.CustomerAddress CA, SalesLT.Address A
join SalesLT.CustomerAddress
on SalesLT.Address.AddressID=SalesLT.CustomerAddress.AddressID
join SalesLT.Customer
on SalesLT.CustomerAddress.CustomerID=SalesLT.Customer.CustomerID
join SalesLT.Address
on SalesLT.CustomerAddress.AddressID=SalesLT.Address.AddressID
Where SalesLT.Customer.FirstName = 'Virginia'
Yeah I am new and not understanding joins very well. Any nudges in the correct direction are much appreciated!
The point of a select statement is to get some data back in a specific way. This takes roughly the following form:
1 – Now, the bit you’ve having the problem with seems to be the middle bit – we’ll do that first.
You’ve got three tables which contain the data you want back in:
And you want to join them together on the columns where the data relate to each other, in this case CustomerID. The inner join statement takes the following form (choosing inner join since all entries have a match in the other tables!):
and if we match up your example to this syntax, we get this:
Now the rest of the select statement sees this query as one big “collection” of data, almost as if it was one table – only each column is pre-fixed by the table name. Where you reference one elsewhere in the statement it isn’t always necessary to include the fully qualified name (as it can guess as long as there isn’t more than one column with the same name in the result set).
2 – The filtering where clause you seem to have got the hang of, but you only seem to be filtering on first name, despite your initial requirements. Adding an additional one is easy:
3 – Finally there is the small matter of what you want back – this you already had correct.
Combining what we’ve done together, you get the following query: