Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's one way to go about building the complete query step by step:</p> <ol> <li><p>Get all search events:</p> <pre><code>SELECT * FROM events AS s WHERE event = 'search' AND condition IS TRUE </code></pre></li> <li><p>Filter out those that are followed by a successful purchase event:</p> <pre><code>SELECT * FROM events AS s LEFT JOIN events AS p ON s.user = p.user AND s.session = p.session AND p.event = 'purchase' AND p.condition IS TRUE AND p.date &gt; s.date -- this assumes that `date` stores both date and time WHERE s.event = 'search' AND s.condition IS TRUE AND p.event IS NULL </code></pre></li> <li><p>Get users from the <code>users</code> table whose IDs are returned in the previous result set and whose age is above 18:</p> <pre><code>SELECT * FROM users WHERE age &gt; 18 AND user IN ( SELECT s.user FROM events AS s LEFT JOIN events AS p ON s.user = p.user AND s.session = p.session AND p.event = 'purchase' AND p.condition IS TRUE AND p.date &gt; s.date WHERE s.event = 'search' AND s.condition IS TRUE AND p.event IS NULL ) ; </code></pre></li> </ol> <p>This should give you the desired results although not necessarily in the most efficient way. You could play with the anti-join, which in this query is implemented using the <code>LEFT JOIN + WHERE IS NULL</code> technique, rewriting it with the <code>NOT EXISTS</code> one to see if that performs any better. Additionally, you could try rewriting the <code>IN</code> predicate with an equivalent <code>EXISTS</code> one. (Essentially, @Roman Pekar's first solution could be viewed as the result of both rewritings suggested.)</p>
    singulars
    1. This table or related slice is empty.
    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.
    1. VO
      singulars
      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