开发者

UPDATE where timestamp is the latest

I have a group of records all with the same data except the timestamp (Yeah, not my design)

Example:

record_id, user, tmstmp
1, myself, 2006-11-15 09:56:14.325882-05
1, myself, 2006-11-15 09:开发者_JAVA百科56:19.051823-05
1, myself, 2006-11-15 11:23:30.581366-05
etc...

Now I would like to UPDATE the record with the latest timestamp. Here is what I'm trying with no luck yet:

UPDATE tbl
SET user = 'TESTING'
WHERE record_id = 1
ORDER BY tmstmp DESC
LIMIT 1

The ORDER BY throws the syntax error.

I think it should be a AND condition but not seeing how. Any thoughts?

PostgreSQL is my db.


UPDATE tbl SET user = 'TESTING'
WHERE record_id = 1
AND tms_tmp in (select max(tms_tmp) from tbl where record_id = 1)


UPDATE  mytable
SET     user = 'TESTING'
WHERE   ctid =
        (
        SELECT  ctid
        FROM    mytable
        WHERE   record_id = 1
        ORDER BY
                tmstmp DESC
        LIMIT 1
        )

This will correctly handle duplicates on tmstmp, if any.


Using PL/pgsql:

DECLARE
  cur CURSOR(key int) FOR
    SELECT * FROM tbl WHERE tbl.record_id = key ORDER BY tmstmp DESC FOR UPDATE;
BEGIN
  OPEN cur(1); -- record_id
  MOVE NEXT FROM cur;
  UPDATE tbl SET "user" = 'TESTING' WHERE CURRENT OF cur;
  CLOSE cur;
END

You can do this in a DO block (from version 9.0) or a function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜