SQL Server 提取多个记录的SQL联接

tkqqtvp1  于 2022-12-17  发布在  其他
关注(0)|答案(2)|浏览(149)

我需要在一个查询中找到所有教师和家长的名字和电子邮件地址
下面是该表的结构:

// Patients Table
ID        guid             parentID     PatientName
1          234               1258      John
2          xyz               111       Paul

// Patient_teacher table
ID          PatiendGuid      teacherid    
1                122            132
2                xyz            1424
3                245            1545
4                xyz            1222

// Members table 
ID                 guid        email                   fname
22                 123        hello@xyz.com            hello
111                xyz        parentEmail@xyz.com      parentName
1424               343        teacherEmail@xyz.com     teacherName
1222               546        teacher2EMail@xyz.com    teacher2Name

下面是所需的结果:

//Required Result

fname        Email
parentName   parentEmail@xyz.com
techerName   teacherEmail@xyz.com
teacher2Name teacher2Email@xyz.com

问题是,当我尝试使用连接进行搜索时,我发现了一个包含parentID和TeacherID的行
下面是我的尝试:

select Members.email,Members.fname
from Members
    join Patients on Members.guid = Patients.guid
    join Patient_Teacher on Patient_Teacher.patientguid = Patients.guid
where patients.guid = 'xyz'
sbdsn5lh

sbdsn5lh1#

以下是解决方案:

select  Members.id, Members.email, Members.fname
from Patients
join Patient_Teacher on Patient_Teacher.patientguid = Patients.guid
join Members on (Patient_Teacher.teacherid = Members.id 
or Patients.parent = Members.id)

where patients.guid = 'xyz'
elcex8rz

elcex8rz2#

您是否检查了以下原因?
1-您有一个名为'Patients_teacher'的表,但在您的解决方案中,您将其称为'Patient_teacher'
2-在'Patients_teacher'表中,您有一个名为'patiendguid'的列,但在您的解决方案中,您将其称为'patientguid'

相关问题