title: Use join for three tables
body: <p>I have three tables and I would like sum over values by month from three tables.</p>
  
  <p>The structure of database:</p>
  
  <pre><code>1)costs_1
  
  -id
  -total
  -updated_at(timestamp)
  
  2)costs_2
  
  -id
  -total_1
  -updated_at_1(timestamp)
  
  3)costs_3
      -id
      -total_2
      -updated_at_2(timestamp)
  </code></pre>
  
  <p>Structure of result table: 1)total; 2)total_1; 3)total_2; 4)month</p>
  
  <p>I have code that work for two tables, but don't know how to adapte it</p>
  
  <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
  <div class="snippet-code snippet-currently-hidden">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>        SELECT t1.y year,
             t1.m month,
             COALESCE(t1.total, 0),
             COALESCE(t2.total, 0)
                 
          FROM
          (
              SELECT YEAR(date_month) y, 
                     MONTH(date_month) m, 
                     SUM(total) total
              FROM market_costs
              GROUP BY YEAR(date_month), MONTH(date_month) 
          ) t1
          LEFT JOIN
          (
              SELECT YEAR(date_month) y, 
                     MONTH(date_month) m, 
                     SUM(total) total
              FROM general_costs
              GROUP BY YEAR(date_month), MONTH(date_month) 
          ) t2 ON t1.y = t2.y and t1.m = t2.m
          
             UNION
          
          SELECT t2.y year,
                 t2.m month,
                 COALESCE(t1.total, 0),
                 COALESCE(t2.total, 0)
          FROM
          (
              SELECT YEAR(date_month) y, 
                     MONTH(date_month) m, 
                     SUM(total) total
              FROM market_costs
              GROUP BY YEAR(date_month), MONTH(date_month) 
          ) t1
          RIGHT JOIN
          (
              SELECT YEAR(date_month) y, 
                     MONTH(date_month) m, 
                     SUM(total) total
              FROM general_costs
              GROUP BY YEAR(date_month), MONTH(date_month) 
          ) t2 ON t1.y = t2.y and t1.m = t2.m</code></pre>
  </div>
  </div>
  </p>