从与主ID键链接的其他表中添加名称

时间:2013-03-14 17:40:07

标签: mysql sql

我有3张名为Doctor,Appointment和Person的表。我需要将医生的名字添加到以下结果中:

enter image description here

使用此代码:

SELECT doctor.doctor_id, COUNT(appointment.appt_time) AS No_APP 
FROM doctor
LEFT JOIN appointment 
ON appointment.doctor_id = doctor.doctor_id
GROUP BY doctor.doctor_id;

我可以对它进行哪些修改,以便我可以使用它的医生名称,这是我的表格列表(名称在他们的doctor_id的人员表中):

enter image description here

1 个答案:

答案 0 :(得分:2)

SELECT
    doctor.doctor_id,
    person.last_name,
    COUNT(appointment.appt_time) AS No_APP 
FROM
    doctor
LEFT JOIN
    appointment  ON appointment.doctor_id = doctor.doctor_id
LEFT JOIN
    person  ON doctor.doctor_id = person.person_id
GROUP BY
    doctor.doctor_id,
    person.last_name;

或者你甚至可以跳过doctor表:

SELECT
    person.person_id,
    person.last_name,
    COUNT(appointment.appt_time) AS No_APP 
FROM
    person
LEFT JOIN
    appointment ON appointment.doctor_id = person.person_id
GROUP BY
    person.person_id,
    person.last_name;