简体   繁体   English

SQL查询以获取ID1的最新条目

[英]SQL query for fetching latest entry for ID1

I have a schema with following attributes: 我有一个具有以下属性的架构:

  1. ID1 ID1
  2. ID2 ID2
  3. Update Date Time 更新日期时间

The primary key of this schema is {ID1,ID2}. 此架构的主键是{ID1,ID2}。 I need to find a the value of ID2 for a given ID1. 我需要找到给定ID1的ID2值。 There will be multiple values for ID2. ID2将有多个值。 I need the one with latest time which I can fetch using "Update Date Time". 我需要一个可以使用“更新日期时间”获取的最新时间。

I have a list of ID1's for which I need to find the corresponding ID2's in one query. 我有一个ID1的列表,我需要在一个查询中找到对应的ID2。

I can do it, using two queries. 我可以使用两个查询来做到这一点。 First of all grouping by ID1 and fetching the max Date Time for the ID1. 首先按ID1分组,并获取ID1的最大日期时间。 And then fetching the ID2 for that "date Time" value(We can assume "Update date Time" is unique for all entries). 然后获取该“日期时间”值的ID2(我们可以假设“更新日期时间”对于所有条目都是唯一的)。

But I was thinking if it is possible to do this is in a single query. 但是我在想是否有可能在单个查询中执行此操作。

I am using MySQL. 我正在使用MySQL。

Assuming your table name is MYTABLE , I have used a subquery to fetch the ID2 value with MAX(UPDATED) for each ID1 value. 假设您的表名是MYTABLE ,我已使用子查询为每个ID1值获取具有MAX(UPDATED)ID2值。 The ID1 values are passed as comma separated values, shown as LIST_OF_ID1s . ID1值作为逗号分隔的值传递,如LIST_OF_ID1s所示。

The query below should do just fine: 下面的查询应该很好:

SELECT * FROM MYTABLE T1 where T1.ID1 in (LIST_OF_ID1s)
AND T1.ID2 = 
 (SELECT T2.ID2 FROM MYTABLE T2 
  where T1.ID1 = T2.ID1 
  ORDER BY T2.UPDATED DESC LIMIT 1);

Working SQL Fiddle demo here 在这里工作的SQL Fiddle演示

try this: 尝试这个:

    SELECT t0.ID1,t0.ID2,t0.Update_date_time
    FROM table AS t0
    LEFT JOIN table AS t1 ON t0.ID1=t1.ID1 AND t1.Update_date_time>t0.Update_date_time
    WHERE t1.ID1 IS NULL;

done in fiddle http://sqlfiddle.com/#!9/8e3879/8/0 在小提琴中完成http://sqlfiddle.com/#!9/8e3879/8/0

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

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