Multiple Table Joins
I have an issue where I need to ONLY get a few things from my initial table, and then join another item from another table, and then joi开发者_JAVA百科n one more item from another table. I thought this would be easy, but it is far from it. Here's my SQL information (kept it to one record for simplicity).
select * from customers limit 1 \G;
*************************** 1. row ***************************
CustomerID: 9
CustomerMapsco: 459
CustomerActive: 1
CustomerFirstName: John
CustomerLastName: Doe
CustomerServiceStreet: 1314 Road Rd.
CustomerServiceCity: City
CustomerServiceState: TX
CustomerServiceZip: 12345
CustomerBillingStreet: 1314 Road Rd.
CustomerBillingCity: City
CustomerBillingState: TX
CustomerBillingZip: 12345
CustomerHomePhone: 1231231234
CustomerCellPhone: 1231231234
CustomerWorkPhone: 1231231234
CustomerWorkExt: 12345
CustomerFax: 1231231324
CustomerEmail: email@tld.COM
CustomerDog: 0
CrewID: 1
ScheduleID: 1
protected: 1
mysql> select * from customerservice limit 1 \G;
*************************** 1. row ***************************
CustomerSvcID: 15
CustomerID: 9
ServiceTypeID: 1
FrequencyTypeID: 1
DayID: 5
CustomerSvcCost: 21
CustomerSvcBeginDate: 2007-01-01 00:00:00
CustomerSvcEndDate: NULL
1 row in set (0.00 sec)
mysql> select * from frequency
-> ;
+-----------------+---------------+
| FrequencyTypeID | FrequencyType |
+-----------------+---------------+
| 1 | Weekly |
| 2 | Biweekly |
| 3 | One Time |
+-----------------+---------------+
What I need is the following columns:
customers.CustomerID, customers.CustomerActive, customers.protected, frequency.FrequencyType
I figured I'd have to do a triple join to get the FrequencyType from the customerservice table as they only referenced in that table, rather than the customer table. So therefore, I have to take one extra step to get that information (customers <> customerservice <> frequency
).
You are right, you need to join all the three tables to get that information, this should be enough:
SELECT c.CustomerID, c.CustomerActive, c.protected, f.FrequencyType
FROM customers c
JOIN customerservice s
ON c.CustomerID = s.CustomerID
JOIN frequency f
ON s.FrequencyTypeID = f.FrequencyTypeID
SELECT c.CustomerID, c.CustomerActive, c.protected, f.FrequencyType
FROM customers c
LEFT JOIN customerservice cs
INNER JOIN frequency f
ON cs.FrequencyTypeID = f.FrequencyTypeID
ON c.CustomerID = cs.CustomerID
精彩评论