Note that there are some explanatory texts on larger screens.

plurals
  1. POLast order timestamp per product
    primarykey
    data
    text
    <p>I want to find the <strong>last payment</strong> (or <code>NULL</code> if n/a) made for which specified <code>product_id</code>. Below is a representation of the tables I'm working with (simplified version).</p> <pre><code>+----------+ |Products | |----------+ |product_id| +----------+ +---------------+ |Orders | +---------------+ |order_id | |order_timestamp| |order_status | +---------------+ +-----------------+ |ProductsOrdersMap| +-----------------+ |product_id | |order_id | +-----------------+ </code></pre> <p>After JOINs, MAXs, GROUP BYs, LEFT JOINs, multiple INNER JOINs to get the greatest-n-per-group, I still can't get to the right result. Most of the times, products with multiple orders are returning multiple rows. The best results I got so far were (I was searching specific products):</p> <pre><code>product_id order_id order_timestamp order_status 8 NULL NULL NULL 9 NULL NULL NULL 10 NULL NULL NULL 12 NULL NULL NULL 13 NULL NULL NULL 14 11 2013-08-13 07:22:01 finished 15 11 2013-08-13 07:22:01 finished 15 12 2013-08-14 00:00:00 finished 32 11 2013-08-13 07:22:01 finished 83 9 2013-08-13 07:04:02 finished 83 10 2013-08-13 07:11:42 finished </code></pre> <p><strong>Edit:</strong> After PP. anwser, I ended up with the following query:</p> <pre><code>SELECT p.product_id, o.order_id, MAX(order_timestamp) AS order_timestamp, order_status FROM Products p LEFT JOIN (ProductsOrdersMap m, Orders o) ON (p.product_id = m.product_id AND m.order_id = o.order_id) WHERE p.product_id IN (8,9,10,12,13,14,15,32,83) GROUP BY p.product_id </code></pre> <p>Which returns</p> <pre><code>product_id order_id order_timestamp order_status 8 NULL NULL NULL 9 NULL NULL NULL 10 NULL NULL NULL 12 NULL NULL NULL 13 NULL NULL NULL 14 11 2013-08-13 07:22:01 finished 15 11 2013-08-13 07:22:01 finished 32 11 2013-08-13 07:22:01 finished 83 9 2013-08-13 07:04:02 finished </code></pre> <p>At first glance, it seems correct but only the products IDs and the timestamps are right. Comparing the two queries above, you can see that, for products 15 and 83, <code>order_id</code> is wrong (<code>order_status</code> might be wrong as well).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload