Difficulty in grouping and where clause in MySql

3

I need to search the database for the last 4 most recent records, with the exr_exa_id column matching the reported id's, and exr_exa_id can not be duplicated.

I tried to group in a few ways, but I was not successful, because it either does not display the most recent records, or it displays equal records in the exr_exa_id column (see image).

Can you help me?

SELECT * 
FROM exa_exameresultado 
WHERE 
   exr_exa_id IN (18,19,20,71) AND 
   exr_pac_id = 2128 
ORDER BY 
   exr_data DESC, 
   exr_exa_id ASC 
LIMIT 4

    
asked by anonymous 13.08.2015 / 20:30

1 answer

1
SELECT 
  * 
FROM 
  exa_exameresultado 
WHERE 
  exr_exa_id IN (18,19,20,71) 
AND 
  exr_pac_id = 2128 
GROUP BY 
  exr_exa_id
ORDER BY 
   exr_data DESC, exr_exa_id ASC 
LIMIT 4

The only change I made was to put a GROUP BY exr_exa_id . But GROUP BY works in this case because the other fields are equal in their values as well. If their values change later, this SELECT may no longer work for you.

    
13.08.2015 / 21:08