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