Update: After re-reading the thread, it appears that I misunderstood the OPs requirements--I was allowing a timestamp to be updated that may be less than the maximum one in the table. The code should be more like:

$ST=$DBH->prepare(<<EOSQL); if not exists (select * from tbl where timestamp > ?) if exists (select * from tbl where hostname=?) update tbl set timestamp=? where hostname=? else insert tbl (hostname, timestamp) values (?, ?) EOSQL $ST->execute($timestamp, $hostname, $timestamp, $hostname, $hostname, +$timestamp);
ewhitt:

Let SQL do some of the work for you:

$ST=$DBH->prepare(<<EOSQL); if not exists (select * from tbl where hostname=?) insert tbl (hostname, timestamp) values (?, ?) else if not exists (select * from tbl where hostname=? and timestamp>?) update tbl set timestamp=? where hostname=? EOSQL $ST->execute($hostname, $hostname, $timestamp, $hostname, $timestamp, $timestamp, $hostname);

Note: I would actually use a stored procedure so I wouldn't have to repeat the $hostname and $timestamp variables in an odd order. But I'm not a MySQL user, so I thought I'd do it with basic SQL.

This way, there's only one transaction with the database for each update: You just give the database a hostname and timestamp with a couple of decisions, and it'll do the rest.

Usual disclaimers apply: Untested code, et cetera.

...roboticus

In reply to Re: Selecting most recent MySQL timestamp by roboticus
in thread Selecting most recent MySQL timestamp by ewhitt

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.