title: Mysql left join and sum
body: <p>I have three table and i need sum amount separately. Also i will use fields on select or where clause.</p>
  
  <pre><code>SELECT i.*, x.* FROM items AS i 
   LEFT JOIN
   (
     SELECT
     p.item_id
     ,SUM(p.amount) AS saleAmount
     ,SUM(IF(p.type=1,pa.amount,0)) AS paidAmount
     FROM payments AS p
     LEFT JOIN payment_actions AS pa ON pa.payment_id=p.id
     GROUP BY p.id
  ) AS x ON x.item_id=i.id
  </code></pre>
  
  <p>items table; </p>
  
  <pre><code>id  
  ---
  1
  </code></pre>
  
  <p>payments table; </p>
  
  <pre><code>id  |   item_id |   amount
  ---------------------------
  1   |   1       |   300 
  </code></pre>
  
  <p>payment_actions table; </p>
  
  <pre><code>id  |   payment_id  |   amount
  ---------------------------
  1   |   1           |   100 
  1   |   1           |   50
  </code></pre>
  
  <p>The result should be; </p>
  
  <pre><code>saleAmount  | paidAmount
  --------------------------
      300     |   150
  </code></pre>