开发者

SELECT all the newest records distinct

开发者 https://www.devze.com 2023-02-15 22:59 出处:网络
i have table structure like this sn|person_id|image_name | 1|开发者_C百科1|abc1.jpb 2|1|aa11.jpg 3|11|dsv.jpg

i have table structure like this

  sn  |  person_id  |   image_name |

   1  |开发者_C百科   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 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 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 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消