title: Rails MySQL subquery with arithmetic
body: <p>I have 3 models:</p>
  
  <ol>
  <li>Product</li>
  <li>Daily Log</li>
  <li>Click</li>
  </ol>
  
  <p>The tables look like:</p>
  
  <pre><code>Products
  id
  </code></pre>
  
  <p>,</p>
  
  <pre><code>Daily Logs
  id | product_id | price
  </code></pre>
  
  <p>,</p>
  
  <pre><code>Clicks
  id | product_id | daily_log_id
  </code></pre>
  
  <p>For reporting, I would like to get all products that have accrued more than x cost (based on price per click).</p>
  
  <p>In Ruby, the code might look like </p>
  
  <pre><code>products.select do | p |
    cost = 0
    p.daily_logs.each do | dlog |
      cost += dlog.clicks.count * dlog.price
    end
  
    cost &gt; x ? true : false      
  end
  </code></pre>
  
  <p>How might I write a similar query for mysql?</p>
  
  <p>Thanks!</p>