Вопрос

I am trying to return FirstName, LastName, Line1, City, State, and ZipCode from the Customers table and the Addresses table using a join. I am to return one row for each customer, but only return addresses that are the shipping address for a customer. This is what I have so far:

SELECT FirstName, LastName, Line1, City, State, ZipCode
FROM Customers JOIN Addresses
    ON (Customers.CustomerID = Addresses.CustomerID);

These are the fields for the Customers table:

CustomerID EmailAddress Password FirstName LastName ShippingAddressID BillingAddressID 

These are the fields for the Addresses table:

AddressID CustomerID Line1 Line2 City State ZipCode Phone Disabled

I tried to use a ad hoc relationship and it did not work. I do not know how to filter out only the shipping address.

Это было полезно?

Решение

Your join has to be based on AddressIds, not CustomerIds, ie:

SELECT FirstName, LastName, Line1, City, State, ZipCode
FROM Customers JOIN Addresses
ON (Customers.ShippingAddressId = Addresses.AddressID);

Другие советы

I think as you are using inner join which is issue, it will bring record if exists in both table, instead use Left join.

SELECT FirstName, LastName, Line1, City, State, ZipCode
FROM Customers Left JOIN Addresses
    ON Customers.CustomerID = Addresses.CustomerID and Customers.ShippingAddressId = Addresses.AddressID;

Do you mean, you need to return Customer detail even if doesn't have an address.

If so, use Left Join

SELECT FirstName, LastName, Line1, City, State, ZipCode
FROM Customers LEFT JOIN Addresses
    ON (Customers.CustomerID = Addresses.CustomerID and 
Customers.ShippingAddressID=Addresses.AddressID)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top