[英]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 我需要不同的person_id最新行如下
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. table是你的表名。
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
然后它按person_id分组(将结果限制为每人id 1)...按SN降序排序意味着它将返回最近(最高)的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
. 您在括号内所做的是选择具有该不同
person_id
的行的最大id
。 So for each unique person_id
you are getting the most recent entry. 因此,对于每个独特的
person_id
您将获得最新的条目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.