Your original method is two queries. You first query for the unique values and then go over every row of it and repeatedly launch a new query to fetch the related value. Fetching related values is usually called a 'join' in relational-database speak.

It happens that relational databases are veeery good at joins. It's what they do for a living. What I did was that I actually changed your two queries into... well, two queries that are linked by a join. That way they will be sent to the database just once, the database figures out the result, and returns it to your program.

The one query in parentheses with the max() is known as a subquery and it returns an intermediate resultset. It's basically a second (temporary) table. It fills the role of your LIMIT 1 query, except that it returns all the related rows rather than just one.

This temporary resultset is then joined against the main table where the id and rpt_key columns match. This gives you the resultset you previously used Perl to build -- in a single query.

You can take the two small queries out of the big query and run them against the database and examine the result to see what they return and how it works.

If you work with relational databases, you really ought to learn SQL to a level that is above the very basic SELECTs and INSERTs. It'll require some stretching of the brain but it's worth it.


In reply to Re^5: Much slower DBI on RHEL6 by Anonymous Monk
in thread Much slower DBI on RHEL6 by MPM

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.