简体   繁体   中英

SQL query for fetching latest entry for ID1

I have a schema with following attributes:

  1. ID1
  2. ID2
  3. Update Date Time

The primary key of this schema is {ID1,ID2}. I need to find a the value of ID2 for a given ID1. There will be multiple values for 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.

I can do it, using two queries. First of all grouping by ID1 and fetching the max Date Time for the ID1. And then fetching the ID2 for that "date Time" value(We can assume "Update date Time" is unique for all entries).

But I was thinking if it is possible to do this is in a single query.

I am using MySQL.

Assuming your table name is MYTABLE , I have used a subquery to fetch the ID2 value with MAX(UPDATED) for each ID1 value. The ID1 values are passed as comma separated values, shown as 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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