0

我有三个表,分别称为ClinicDoctorClinic_has_Doctor。假设这两个表ClinicDoctor具有字段idname如下所示:

Clinic 
+----+------------------------+
| id | name                   |
+----+------------------------+

Doctor
+----+------------------------+
| id | name                   |
+----+------------------------+

并且Clinic_has_Doctor是一个包含诊所和医生之间映射的简单表:

Clinic_has_Doctor
+-----------+-----------------+
| Clinic_id | Doctor_id       |
+-----------+-----------------+

Clinic预计是和DoctorID的外键。我需要得到诊所的名单和他们旁边的医生。所以我会有一张像这样的桌子:

+-----------+--------------+------------+--------------+
| Clinic_id | Clinic_name  | Doctor_id  | Doctor_name  |
+-----------+--------------+------------+--------------+

我没有做太多的JOINSQL 命令,所以我无法摆脱这个。有什么帮助吗?

4

2 回答 2

4

您将希望JOIN使用您的表Clinic_has_Doctor连接ClinicDoctor表:

select c.id ClinicId,
  c.name ClinicName,
  d.id DoctorId,
  d.name Doctor_name
from clinic c
inner join Clinic_has_Doctor cd
  on c.id = cd.clinic_id
inner join doctor d
  on cd.Doctor_id = d.id

如果您在学习JOIN语法方面需要帮助,那么这里有一个很好的连接可视化解释

INNER JOIN在查询中使用了一个,它将返回所有Clinics与他们相关联的医生。

如果您想返回一个Clinics即使没有相关医生的列表,那么您将使用LEFT JOIN

select c.id ClinicId,
  c.name ClinicName,
  d.id DoctorId,
  d.name Doctor_name
from clinic c
left join Clinic_has_Doctor cd
  on c.id = cd.clinic_id
left join doctor d
  on cd.Doctor_id = d.id
于 2013-02-03T18:39:01.497 回答
2

应该是这样的:

select clinic_has_doctor.clinic_id
     , clinic.clinic_name
     , clinic_has_doctor.doctor_id
     , doctor.doctor_name
from   clinic_has_Doctor 
join   clinic 
on     clinic.id=clinic_has_Doctor.clinic_id
join   doctor
on     doctor.id=clinic_has_Doctor.doctor_id
于 2013-02-03T18:39:46.013 回答