SET SESSION sql_mode = "";
SELECT
	p.patient_unique_id,
	p.patient_name,
	p.age,
	p.gender,
	odaj.*
FROM
	patients AS p
INNER JOIN (
		SELECT
			oda.appointment_no,
			oda.patient_id,
			oda.appointment_status,
			oda.doctor_appointment_date,
			oda.doctor_id,
			doctors.doctor_name
		FROM
			opd_doctor_appointments AS oda 
		INNER JOIN doctors ON doctors.id = oda.doctor_id
		WHERE
			oda.id IN ( SELECT MAX( odaa.id ) FROM opd_doctor_appointments as odaa GROUP BY odaa.patient_id )
		ORDER BY oda.created_at DESC
	) AS odaj ON odaj.patient_id = p.id
WHERE
	odaj.appointment_status IN ( 'B', 'C' )