MySQL三表连接

时间:2013-02-03 18:32:40

标签: mysql join multiple-tables

我有三个名为ClinicDoctorClinic_has_Doctor的表格。假设两个表ClinicDoctor包含字段idname,如下所示:

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

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

Clinic_has_Doctor是一个简单的表格,其中包含诊所和医生之间的映射:

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

预计是ClinicDoctor ID的外键。我需要获得诊所和医生的清单。所以我会有一个像这样的表:

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

我没有做过多JOIN个SQL命令,所以我无法摆脱这个问题。有什么帮助吗?

2 个答案:

答案 0 :(得分:4)

您需要JOIN使用Clinic_has_Doctor将表格Clinic连接到Doctor表:

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语法,那么这里有一个很棒的visual explanation of joins

我在查询中使用了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

答案 1 :(得分: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