Home > Blockchain >  Group by on same table not return most recent record
Group by on same table not return most recent record

Time:05-31

I have records in appointment table with patient information.When i try to fetch latest patient appointment using group by it doesn't give me right result.I used group by with order by.Attached the table schema and query

enter image description here

Query :

SELECT * FROM `appointment` where appointment.patient = 2650 group by appointment.patient 
order by appointment.id desc 

Above query return record whose id is 6718

Note : In this query i have added where condition only for one patient and i want the all patient latest appointment.

CodePudding user response:

If you have Laravel models setup its as easy as this

Appointment::where('patient', 2650)->orderByDesc('id')->get();

also I don't recommend ordering anything by Id, since you have add_date column I suggest using it like so orderByDesc('add_date')

CodePudding user response:

Did I understand correctly that you only need the last appointment number for each of the patients? If so, does it solve your question? If not, present the expected output, please.

select max(id) as last_appt, patient
from appointment
group by patient
order by patient;

Here's dbfiddle example

  • Related