多个连接到同一个表

时间:2012-06-06 19:59:53

标签: sql join

我有两张表Profile_Appointments和Profile。

除了其他个人资料数据外,个人资料表中的每个记录都有一个Profile_key和一个Profile_Type_Key - 名字,姓氏等。

Rep有Profile_Type 4,客户有Profile_Type 6

 PROFILE TABLE
 Profile_Key    Profile_Type_key    First_Name     Last_Name
  1234                 4              John            Smith
  8765                 6              Mike            Jones

Profile_Appointment表为每个约会保存两个记录,其中包含Rep Profile_Key另一个与客户的Profile_Key

 Appointment_Key        Profile_Key     
     10                    1234
     10                    8765                  

appointment_key指的是约会表。

我需要进行一次查询,为每个约会产生一条记录,并且同时拥有来自个人资料表的代表和客户的数据

 THE RESULT I WANT
 Appointment_Key  Profile_Key Rep    Profile_Key Customer
    10                1234                    8765

这是不起作用的查询...

  select appointment_key, p.profile_key as Rep, p2.profile_key as Customer, p.firs_name,p2.first_name from profile_appointment pa

  join profile p 
  on p.profile_key = pa.profile_key

  join profile p2
  on p2.profile_key = pa.profile_key

  where p.profile_type_key = '4' or p2.profile_type_key = '6' 

我得到的是:

 Appointment_Key      Rep      Customer     Rep      Customer
    10                1234      1234        John       John

我无法弄清楚我错过了什么。 谢谢。

2 个答案:

答案 0 :(得分:1)

SELECT a1.appointment_key, a1.profile_key rep, a2.profile_key customer
  FROM appointment a1
  INNER JOIN profile p1 ON a1.profile_key = p1.profile_key AND p1.profile_type_key = 4
  INNER JOIN appointment a2 ON a1.appointment_key = a2.appointment_key
  INNER JOIN profile p2 ON a2.profile_key = p2.profile_key AND p2.profile_type_key = 6

编辑:您可能会发现嵌套选择更具可读性:

SELECT reps.appointment_key, reps.profile_key rep, customers.profile_key customer
  FROM (
    SELECT appointment.*
      FROM appointment
      INNER JOIN profile ON appointment.profile_key = profile.profile_key AND profile_type_key = 4
  ) reps
  INNER JOIN (
    SELECT appointment.*
      FROM appointment
      INNER JOIN profile ON appointment.profile_key = profile.profile_key AND profile_type_key = 6
  ) customers ON reps.appointment_key = customers.appointment_key

答案 1 :(得分:0)

您需要满足这两个条件,因此您需要AND而不是OR

    select pa.appointment_key, p.profile_key as Rep, p2.profile_key as Customer, 
        p.first_name as RepName,p2.first_name as CustomerName
from profile_appointment pa    
join profile_appointment pa2 on pa.appointment_key = pa2.appointment_key
join profile p    on p.profile_key = pa.profile_key    and  p.profile_type_key = '4'
join profile p2   on p2.profile_key = pa2.profile_key   and  p2.profile_type_key = '6'