我有一个问题,我只需要从初始表中获取一些东西,然后从另一个表中加入另一个项,然后从另一个表中加入另一个项。我以为这很容易,但远不是。这是我的SQL信息(为了简单起见,将它保存在一个记录中)。

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 protected]
          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      |
+-----------------+---------------+

我需要的是以下列:
customers.CustomerID, customers.CustomerActive, customers.protected, frequency.FrequencyType

我想我必须执行三重连接才能从customerservice表中获取FrequencyType,因为它们只在该表中引用,而不是在customer表中引用。因此,我必须采取一个额外的步骤来获取这些信息(customers <> customerservice <> frequency)。

最佳答案

你说得对,你需要把这三个表连接起来才能得到这些信息,这应该足够了:

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

10-04 11:15