I'm using DBD:Pg to connect to a Postgres server. This isn't a Perl question per se, but perhaps someone will be kind enough to answer it anyhow.

I have a table of object records (lb_objs) that are frequently accessed. I keep track of these accesses in another table, lb_trans. lb_trans has columns for the primary key of the object acted on (lb_trans.obj_id), a timestamp (lb_trans.instant), and an access type (lb_trans.action). I'm trying to craft a way to select a set of the objects (e.g. lb_objs.attrib = 1), and include in each returned row the transaction type from the most recent transaction on the object specified by that row. With two queries it's simple:

SELECT id, attrib FROM lb_objs WHERE attrib = 1
followed by, for each result,
SELECT action FROM lb_trans WHERE obj_id = ? ORDER BY instant DESC LIMIT 1
where ? is a placeholder set to lb_objs.id for the current lb_objs row.

However, I'd prefer to do it in one select, since I could reuse that for other similar queries more directly. I've though about using various joins and sub-selects, but I can't find a way to do it. Can anyone see a way to do this with just one select?


In reply to (OT) Postgres Query by Anonymous Monk

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.