title: Two queries are fast separately, slow when joined as subqueries
body: <p>I have two queries that each, on their own, run pretty quickly (less than 2 seconds). However, when I try to join them as subqueries, it runs ridiculously slowly. The last time I ran it it took about 68 seconds. Here's the full query:</p>
  
  <pre><code>SELECT t.count,
         t.total
    FROM (SELECT t.account_number,
                 COUNT(t.id) count,
                 SUM(t.amount) total,
                 ib.id import_bundle_id
            FROM import_bundle ib
            JOIN generic_import gi ON gi.import_bundle_id = ib.id
            JOIN transaction_import ti ON ti.generic_import_id = gi.id
            JOIN account_transaction t ON t.transaction_import_id = ti.id
            JOIN transaction_code tc ON t.transaction_code_id = tc.id
           WHERE tc.code IN (0, 20, 40)
        GROUP BY t.account_number) t
    JOIN (SELECT a.account_number,
                 np.code
            FROM import_bundle ib
            JOIN generic_import gi ON gi.import_bundle_id = ib.id
            JOIN account_import ai ON ai.generic_import_id = gi.id
            JOIN account a ON a.account_import_id = ai.id
            JOIN account_northway_product anp ON anp.account_id = a.id
            JOIN northway_product np ON anp.northway_product_id = np.id
           WHERE np.code != 'O1') a ON t.account_number = a.account_number
  </code></pre>
  
  <p>That this query should run slowly is not a total surprise. If these were two separate tables and not subqueries, I would put indexes on their <code>account_number</code> columns. However, it's obviously not possible to put indexes on query results, so I can't do that. I suspect that's part of the problem.</p>
  
  <p>Aside from that, I don't understand why the query is slow and I don't have any ideas on how to speed it up, other than adding two summary tables, which I don't want to do if I don't have to.</p>
  
  <p>By the way, this query in English might be, "Get all the POS transactions (codes 0, 20 and 40) for accounts that aren't overdraft protection accounts (code O1)."</p>