Hilmy Nur Ramdhani Hilmy Nur Ramdhani - 6 months ago 27
MySQL Question

How to select distinct max value from multiple join table MySQL

This is my current query for selecting data:

select a.No_Registrasi, a.Nama_CTKI, b.Nama_Negara, c.ID_Rad, d.ID_Lab
FROM tb_registrasi a
JOIN tb_negara_tujuan b
ON a.ID_Negara = b.ID_Negara
JOIN tb_radiologi c
ON a.No_Registrasi = c.No_Registrasi
JOIN tb_laboratorium d
ON a.No_Registrasi = d.No_Registrasi


And here's the result:

query result

How do i distinct those ID_Rad and ID_Lab and I need the max value from each ID_Rad and ID_Lab so it will be like this:

result

Answer

Use GROUP BY and MAX, try this;)

select a.No_Registrasi, a.Nama_CTKI, b.Nama_Negara, CONCAT('RA-', MAX(substring(c.ID_Rad, 4) + 0)) AS ID_Rad, CONCAT('Lab-',MAX(substring(d.ID_Lab, 5) + 0)) AS Id_Lab
FROM tb_registrasi a 
JOIN tb_negara_tujuan b
    ON a.ID_Negara = b.ID_Negara
JOIN tb_radiologi c
    ON a.No_Registrasi = c.No_Registrasi
JOIN tb_laboratorium d
    ON a.No_Registrasi = d.No_Registrasi
GROUP BY a.No_Registrasi, a.Nama_CTKI, b.Nama_Negara
Comments