Let me start by saying I am relatively new to MySQL. I am trying to migrate data from one database to another. Let us call one database DB1 and the other DB2.
DB2 has tables the following tables.
Patient: id, person_id and start_regimen_id
Regimen: id, code
Visit: id, patient_id, regimen_id,next_appointment_date
DB1 has the following tables:
Patient: id,medical_record_number,current_regimen, start_regimen nextappointment
Now:
regimen_id data should be inserted to current_regimen
start_regimen_id data should be inserted to start_regimen
next_appointment_date should be inserted to nextappointment
This is what I have now:
SELECT
p.person_id AS medical_record_number,
r.code AS start_regimen,
??? AS current_regimen,
DATE_FORMAT(v.next_appointment_date, '%Y-%m-%d') AS
nextappointment,
FROM patient p
LEFT JOIN regimen r ON r.id = p.start_regimen_id
LEFT JOIN (
SELECT patient_id, MAX(next_appointment_date) as next_appointment_date
FROM visit
WHERE next_appointment_date IS NOT NULL
GROUP BY patient_id
) v ON v.patient_id = p.id
I have remained to migrate regimen_id (visit) on DB2 to current_regimen (patient) on DB1. I don't know how to use two LEFT JOIN to get data from two tables for one table.
Any assistance will be greatly appreciated because I am really stuck.
Seems like we would want to include regimen_id
in the GROUP BY
from the visit
table, and then match that to id
from the regimen
table. Given the outer join, it appears that patient
may not have any regimen
associated, so I would include matching of NULL
values of regimen_id
.
LEFT
JOIN ( SELECT vv.patient_id
, vv.regimen_id
, MAX(vv.next_appointment_date) AS next_appointment_date
FROM visit vv
WHERE vv.next_appointment_date IS NOT NULL
GROUP
BY vv.patient_id
, vv.regimen_id
) v
ON v.patient_id = p.id
AND v.regimen_id <=> r.id
But that's just a guess. Without a specification (preferably illustrated by example data and and expected output) we're just guessing.
Note:
foo <=> bar
is a NULL-safe comparison, a shorthand equivalent to
( foo = bar OR ( foo IS NULL AND bar IS NULL ) )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.