Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT all the newest records distinct

Tags:

mysql

group-by

i have table structure like this

  sn  |  person_id  |   image_name |

   1  |   1         |      abc1.jpb 
   2  |   1         |      aa11.jpg  
   3  |   11        |      dsv.jpg
   4  |   11        |      dssd.jpg
   5  |   11        |      sdf.jpg

I need distinct person_id newest row as following

  2   |  1          |  aa11.jjpb
  5   |  11         |  sdf.jpg

IT is possible ?

like image 826
G-Rajendra Avatar asked Dec 05 '25 13:12

G-Rajendra


1 Answers

SELECT * FROM yourtable GROUP BY person_id ORDER BY sn DESC

Essentially you want to select all records from your table. Then it is grouped by the person_id (limiting the result to 1 per person id)... Ordering by SN decending means that it will return the most recent (highest) sn

Update: (and verified)

SELECT * FROM (SELECT * FROM stackoverflow ORDER BY sn DESC) a GROUP BY person_id ORDER BY sn
like image 166
CarpeNoctumDC Avatar answered Dec 08 '25 01:12

CarpeNoctumDC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!