0

我有两个表 Profile_Appointments 和 Profile。

除了其他配置文件数据(名字、姓氏等)之外,配置文件表中的每条记录都有一个 Profile_key 和一个 Profile_Type_Key。

代表有 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                  

约会键是指约会表。

我需要进行查询,为每个约会生成一条记录,并从 Profile 表中获取代表和客户的数据

 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

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

4

2 回答 2

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
于 2012-06-06T20:12:16.033 回答
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'  
于 2012-06-06T20:26:02.510 回答