简体   繁体   English

MySQL获取组的最后一个元素

[英]Mysql fetch last element of group

Good morning, 早上好,

I am trying to get the most up to date element of a group from the database but no luck so far. 我正在尝试从数据库中获取一组的最新信息,但到目前为止还没有运气。 Ideas anyone? 有任何想法吗? I guess the solution is quite easy but I am really stuck there... 我想解决方案很容易,但是我真的被困在那...

Data: 数据:

+---------------+----------+-------+------------+---------------------+
| transition_id | field_id | value | changed_by | changed             |
+---------------+----------+-------+------------+---------------------+
| 3             | 1        | Data  | Mike       | 2018-08-13 00:00:00 |
| 3             | 2        | Data  | Mike       | 2018-08-13 00:00:00 |
| 3             | 3        | Data  | Mike       | 2018-08-13 00:00:00 |
| 3             | 1        | Data  | Mike       | 2018-08-20 00:00:00 |
| 4             | 1        | Data  | Mike       | 2018-08-15 00:00:00 |
+---------------+----------+-------+------------+---------------------+

Expected results: 预期成绩:

+---------------+----------+-------+------------+---------------------+
| transition_id | field_id | value | changed_by | changed             |
+---------------+----------+-------+------------+---------------------+
| 3             | 2        | Data  | Mike       | 2018-08-13 00:00:00 |
| 3             | 3        | Data  | Mike       | 2018-08-13 00:00:00 |
| 3             | 1        | Data  | Mike       | 2018-08-20 00:00:00 |
| 4             | 1        | Data  | Mike       | 2018-08-15 00:00:00 |
+---------------+----------+-------+------------+---------------------+

Grouping: transition_id, field_id 分组: transition_id,field_id

I tried using a left join on the table itself, but this is only returning a single item. 我尝试在表本身上使用左联接,但这仅返回单个项目。

SELECT t1.* 
FROM table t1 
LEFT JOIN table t2 ON (t1.event = t2.event AND t1.update < t2.update) 
WHERE t2.update IS NULL AND t1.event = 81 

Thank you for your help! 谢谢您的帮助! André 安德烈

Fiddle: http://sqlfiddle.com/#!9/b24ddb/4 小提琴: http ://sqlfiddle.com/#!9/b24ddb/4

Try this : 尝试这个 :

select x.* from tablename x
inner join 
(select event, item, max(update) as mupdate from tablename
group by event, item)a
on x.event=a.event and x.item=a.item and x.update=a.mupdate 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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