1

早上好,

我正在尝试从数据库中获取组的最新元素,但到目前为止还没有运气。任何人的想法?我想解决方案很简单,但我真的被困在那里......

数据:

+---------------+----------+-------+------------+---------------------+
| 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 |
+---------------+----------+-------+------------+---------------------+

预期成绩:

+---------------+----------+-------+------------+---------------------+
| 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 |
+---------------+----------+-------+------------+---------------------+

分组: transition_id、field_id

我尝试在表本身上使用左连接,但这仅返回一个项目。

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 

谢谢您的帮助!安德烈

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

4

1 回答 1

0

尝试这个 :

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 
于 2018-08-20T09:15:53.383 回答