MySql:从另一个表中插入SELECT表,其中first_table ID = another_table.id

时间:2018-04-12 11:23:25

标签: mysql

我有这个起始表:

+----+-------------+---------+
| id | id_customer | balance |
+----+-------------+---------+
|  1 |         123 | NULL    |
|  2 |         124 | NULL    |
|  3 |         125 | NULL    |
|  4 |         126 | NULL    |
+----+-------------+---------+

我需要使用另一个表中的SELECT SUM填充balance列,其中id_customer在first = id_customer中,在第二个表中。

+----+-------------+--------+------------+
| 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 |
+----+-------------+--------+------------+

第二张表的条件是SUM(金额)WHERE date_trans BETWEEN' 2010-01-01' AND' 2018-02-28'。

所以,在我的例子中,我需要最终的第一个表格为:

+----+-------------+---------+
| id | id_customer | balance |
+----+-------------+---------+
|  1 |         123 | 90      |
|  2 |         124 | 20      |
|  3 |         125 | 70      |
|  4 |         126 | 10      |
+----+-------------+---------+

id 2只有20导致id 4的10 $交易超出范围。 id 4只有10因为id 7的50 $交易超出了范围。

这是从second_table中提取SUM的(简单)查询。

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

对于这个查询,我还有几个ID对我来说并不感兴趣,所以我需要做一个类似的伪代码:

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

我无法使用" IN"因为第二个表大约是100.000行。起点大约是600。

3 个答案:

答案 0 :(得分:1)

只需在UPDATE语句的SET子句中使用(相关)子查询:

UPDATE first_table t1
SET t1.balance = (
  SELECT SUM(t2.amount)
  FROM second_table t2
  WHERE t2.date_trans BETWEEN '2010-01-01 00:00:00' AND '2018-02-28 23:59:59'
    AND t2.id_customer = t1.id_customer
);

演示:http://sqlfiddle.com/#!9/9e6aa2/1

答案 1 :(得分:0)

试试这个

update first_table 
set balance = sum(B.Balance)
from first_table A
inner join second_table B on (A.id_customer = B.id_customer
                              and (B.date_trans BETWEEN '2010-01-01 00:00:00' AND '2018-02-28 23:59:59'))
group by B.id_customer 

答案 2 :(得分:0)

试试这个:

UPDATE first_table A JOIN (SELECT id_customer, SUM(amount) total_amount  
                           FROM second_table
                           WHERE date_trans BETWEEN '2010-01-01 00:00:00'
                                                AND '2018-02-28 23:59:59'
                           GROUP BY id_customer) B 
ON A.id_customer=B.id_customer
SET A.balance=B.total_amount;

SQL Fiddle上看到它。

请参阅MySQL UPDATE JOIN教程了解见解。