2

Is there simple way to select updated rows?

I'm trying to store timestamp each time I am read row to be able to delete data that was not readed for a long time.

First I tried execute SELECT query first and even found little bit slow but simple solution like

 UPDATE foo AS t, (SELECT id FROM foo WHERE statement=1)q
 SET t.time=NOW() WHERE t.id=q.id

but I still want to find a normal way to do this.

I also think that updating time first and then just select updated rows should be much easier, but I didn't find anything even for this

George Vinokhodov
  • 327
  • 1
  • 4
  • 10

4 Answers4

4

For a single-row UPDATE in MySQL you could:

UPDATE foo
SET    time = NOW()
WHERE  statement = 1
AND    @var := id

@var := id is always TRUE, but it writes the value of id to the variable @var before the update. Then you can:

SELECT @var;

In PostgreSQL you could use the RETURNING clause.
Oracle also has a RETURNING clause.
SQL-Server has an OUTPUT clause.
But MySQL doesn't have anything like that.

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
2

Declare the time column as follows:

CREATE TABLE foo (
    ...
    time TIMESTAMP ON UPDATE CURRENT_TIMESTAMP(),
    ...)

Then whenever a row is updated, the column will be updated automatically.

UPDATE:

I don't think there's a way to update automatically during SELECT, so you have to do it in two steps:

UPDATE foo
SET time = NOW()
WHERE <conditions>;

SELECT <columns>
FROM foo
WHERE <conditions>;

As long as doesn't include the time column I think this should work. For maximum safety you'll need to use a transaction to prevent other queries from interfering.

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

@Erwin Brandstetter: Not difficult to extend the strategy of using user variables with CONCAT_WS() to get back multiple IDs. Sorry, still can't add comments...

fenway
  • 416
  • 2
  • 8
  • I'm not really good at sql, how can I get back ids from result string? – George Vinokhodov Feb 23 '13 at 10:01
  • Depends on your actual UPDATE statement; but something along the lines of (re-)setting a known user variable within the query, appending each ID to the variable, and then retrieving it thereafter. – fenway Feb 24 '13 at 21:01
0

As suggested here you can extract the modified primary keys to update their timestamp column afterwards.

SET @uids := null;
UPDATE footable
   SET foo = 'bar'
 WHERE fooid > 5
   AND ( SELECT @uids := CONCAT_WS(',', fooid, @uids) );
SELECT @uids;

from https://gist.github.com/PieterScheffers/189cad9510d304118c33135965e9cddb

So you should replace the final SELECT @uids; with an update statement by splitting the resulting @uids value (it will be a varchar containing all the modified ids divided by ,).