I am currently working with a database table design structured as follows:
Table Appointments:
id| start_time| patientId |.. and other fields |
And another table known as the Patient table:
id| name | last_name | .. along with other fields |
In my appointment entity, I have defined the following:
@OneToMany(() => AppointmentEntity, (appt) => appt.patient)
appointments: Relation<AppointmentEntity>[];
The goal is to retrieve appointment details along with the patient's first name using only one query when given an appointment id. This is how I achieved it:
async getAppt(apptId: any) {
return this.apptRepo.findOne({
relations: ['patient'],
where: { id: apptId },
select: {
id: true,
start_time: true
patient: {
name: true,
},
},
});
}
Although this method provides me with the desired outcome, I noticed that it executes two unnecessary database queries instead of just one. The following queries are triggered each time getAppt
is called:
query: SELECT DISTINCT "distinctAlias"."AppointmentEntity_id" AS "ids_AppointmentEntity_id" FROM (SELECT "AppointmentEntity"."id" AS "AppointmentEntity_id", "AppointmentEntity"."start_time" AS "AppointmentEntity_start_time", "AppointmentEntity__AppointmentEntity_patient"."name" AS "AppointmentEntity__AppointmentEntity_patient_name" FROM "appointments" "AppointmentEntity" LEFT JOIN "patients" "AppointmentEntity__AppointmentEntity_patient" ON "AppointmentEntity__AppointmentEntity_patient"."id"="AppointmentEntity"."patientId" WHERE ("AppointmentEntity"."id" = $1)) "distinctAlias" ORDER BY "AppointmentEntity_id" ASC LIMIT 1 -- PARAMETERS: ["appt_id_xxx"]
query: SELECT "AppointmentEntity"."id" AS "AppointmentEntity_id", "AppointmentEntity"."start_time" AS "AppointmentEntity_start_time", "AppointmentEntity__AppointmentEntity_patient"."name" AS "AppointmentEntity__AppointmentEntity_patient_name" FROM "appointments" "AppointmentEntity" LEFT JOIN "patients" "AppointmentEntity__AppointmentEntity_patient" ON "AppointmentEntity__AppointmentEntity_patient"."id"="AppointmentEntity"."patientId" WHERE ( ("AppointmentEntity"."id" = $1) ) AND ( "AppointmentEntity"."id" IN ($2) ) -- PARAMETERS: ["appt_id_xxx","appt_id_xxx"
What I truly intended was for the query execution to be streamlined into just one query, similar to the example below:
select b.id, b.start_time, p.name from appointments b
inner join patients p on p.id = b."patientId"
where b.id = 'appt_id_xxx';
I prefer not to include aliases "b" and "p", but I require a more efficient approach like the above. The inclusion of distinctAlias
and the duplicate queries are perplexing. Any insights on achieving a single query (or equivalent) would be greatly appreciated. Thank you!