简体   繁体   中英

SELECT all the newest records distinct

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 ?

SELECT * FROM table GROUP BY person_id HAVING MAX(sn)

EDIT

SELECT f.*
FROM (
      SELECT person_id, MAX(sn) as maxval
      FROM  table GROUP BY person_id
     ) AS x INNER JOIN table AS f
ON f.person_id = x.person_id AND f.sn = x.maxval;

where table is your table name.

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
SELECT * FROM table a WHERE a.`id` = ( SELECT MAX(`id`) FROM table b WHERE b.`person_id` = a.`person_id` );

What you are doing inside the parenthesis is selecting the max id for the rows that have that distinct person_id . So for each unique person_id you are getting the most recent entry.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM