Group by on same table not return most recent record

120

Question: Group by on same table not return most recent record

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 php error 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 php error patient and i want the all patient latest appointment.

Total Answers: 2

55

Answers 1: of Group by on same table not return most recent record

Did I understand correctly that you only need the last appointment number for php error 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

68

Answers 2: of Group by on same table not return most recent record

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')