从table1更新unit2列到table2

时间:2013-09-03 04:37:16

标签: mysql sql sql-update sum

表:

mysql> select * from table1;
+------+------+------+
| no   | nm   | unit |
+------+------+------+
|    1 | ABC  |   10 |
|    2 | ACX  |   20 |
|    3 | AYU  |   30 |
+------+------+------+
3 rows in set (0.01 sec)

mysql> select * from table2;
+------+------+------+
| no   | nm   | unit |
+------+------+------+
|    1 | ABC  |   40 |
|    2 | ACX  |   20 |
+------+------+------+
2 rows in set (0.00 sec)

必填项:

mysql> select * from table2;
+------+------+------+
| no   | nm   | unit |
+------+------+------+
|    1 | ABC  |   50 |
|    2 | ACX  |   40 |
|    3 | AYU  |   30 |
+------+------+------+
3 rows in set (0.00 sec)

4 个答案:

答案 0 :(得分:1)

如果要根据需要更新Table2,则需要先更新已存在的行,然后从Table1插入新行:

您可以使用JOIN更新单位:

UPDATE Table2 t2
  JOIN 
       (SELECT nm, SUM(unit) unit
       FROM
       (
           SELECT * FROM Table1 t1
           UNION ALL
           SELECT * FROM Table2 t2
       ) tbl
       GROUP BY nm
       ) tbl1
    ON t2.nm = tbl1.nm
   SET t2.unit = tbl1.unit;

然后你可以在Table2中添加Table2中不存在的行(例如nm=AYU

INSERT INTO Table2
SELECT t1.`no`, t1.`nm`, t1.`unit`
  FROM Table1 t1
  LEFT JOIN Table2 t2
    ON t1.nm = t2.nm
 WHERE t2.nm IS NULL;

输出:

SELECT * FROM Table2;
| NO |  NM | UNIT |
|----|-----|------|
|  1 | ABC |   50 |
|  2 | ACX |   40 |
|  3 | AYU |   30 |

请参阅this SQLFiddle

记住首先更新表格。否则它将复制单位。

答案 1 :(得分:0)

我环顾四周,看到this answer我认为更合理,算术应该在数据库操作之外完成。但是如果您希望使用SQL,我将在稍后将其编辑为此答案。

答案 2 :(得分:0)

如果您只想从两个表中选择数据作为所需输出,请尝试:

SELECT MIN(no) NO, nm, SUM(unit) unit
FROM
(
    SELECT * FROM Table1 t1
    UNION ALL
    SELECT * FROM Table2 t2
) tbl
GROUP BY nm;

输出:

| NO |  NM | UNIT |
|----|-----|------|
|  1 | ABC |   50 |
|  2 | ACX |   40 |
|  3 | AYU |   30 |

请参阅this SQLFiddle

答案 3 :(得分:0)

选择

不,nm sum(单位)

来自

从table1中选择*

联合所有

从table2中选择*

)作为temp group by no,nm;