title: MySql: insert into table SELECT from another table where first_table ID =another_table.id
body: <p>I have this starting table:</p>
  
  <pre><code>+----+-------------+---------+
  | id | id_customer | balance |
  +----+-------------+---------+
  |  1 |         123 | NULL    |
  |  2 |         124 | NULL    |
  |  3 |         125 | NULL    |
  |  4 |         126 | NULL    |
  +----+-------------+---------+
  </code></pre>
  
  <p>I need to populate that <code>balance</code> column with a SELECT SUM from another table, where id_customer in first = id_customer in second one.</p>
  
  <pre><code>+----+-------------+--------+------------+
  | id | id_customer | amount | date_trans |
  +----+-------------+--------+------------+
  |  1 |         123 |    100 | 2018-01-01 |
  |  2 |         123 |    -10 | 2018-01-04 |
  |  3 |         125 |     70 | 2018-01-01 |
  |  4 |         124 |     10 | 1994-05-04 |
  |  5 |         124 |     20 | 2018-01-01 |
  |  6 |         126 |     10 | 2018-01-16 |
  |  7 |         126 |     50 | 2018-04-16 |
  +----+-------------+--------+------------+
  </code></pre>
  
  <p>Condition of second table is SUM (amount) WHERE date_trans BETWEEN '2010-01-01' AND '2018-02-28'.</p>
  
  <p>So, in my example, I need final first table as:</p>
  
  <pre><code>+----+-------------+---------+
  | id | id_customer | balance |
  +----+-------------+---------+
  |  1 |         123 | 90      |
  |  2 |         124 | 20      |
  |  3 |         125 | 70      |
  |  4 |         126 | 10      |
  +----+-------------+---------+
  </code></pre>
  
  <p>id 2 only 20 cause the 10$ transaction at id 4 is out of range.
  id 4 only 10 cause the 50$ transaction at id 7 is out of range.</p>
  
  <p>This is the (simple) query to extract from second_table the SUM.</p>
  
  <pre><code>SELECT id_customer , SUM(balance) AS saldo FROM second_table
  WHERE date_trans BETWEEN '2010-01-01 00:00:00' AND '2018-02-28 23:59:59'
  GROUP BY id_customer
  </code></pre>
  
  <p>WIth this query I have also several IDs (~99400) that are not interesting for me, so I need to do a similar psuedocode:</p>
  
  <pre><code>INSERT INTO first_table ( balance ) 
  SELECT saldo FROM
  ( SELECT id_customer , SUM(balance) AS saldo FROM second_table
      WHERE date_trans BETWEEN '2010-01-01 00:00:00' AND '2018-02-28 23:59:59'
      GROUP BY id_customer )
  WHERE first_table.id_customer = second_table.id_customer
  </code></pre>
  
  <p>I cannot use "IN" because second table are about 100.000 rows. Starting table are about 600.</p>