mysql - 根据对另一个表的选择结果更新表

标签 mysql updates bulk bulkupdate

我有两个这样的表:

人:

id | name | sale | commission
1  | abc  | 0    |   0
2  | xyz  | 0    |   0

促销:

id | date       | person_id | sale | commission
1  | 2016-05-01 |     1     | 10   |     1
2  | 2016-05-02 |     1     | 10   |     1
3  | 2016-05-03 |     1     | 10   |     1
4  | 2016-05-01 |     2     | 20   |     2
5  | 2016-05-02 |     2     | 20   |     2
6  | 2016-05-01 |     2     | 20   |     2

我想用单个更新查询来更新 person 表,并像这样更改表:

人:

id | name | sale | commission
1  | abc  | 30   |   3
2  | xyz  | 60   |   6

我知道我可以像下面那样对销售进行求和,但是如何将下面的查询结果直接更新到人员表中。

SELECT person_id, SUM(sale), SUM(commission) 
FROM sale
GROUP BY person_id; 

最佳答案

正如 Strawberry 在您的问题下的评论中所说,在您保存此信息之前请三思而后行。它被非规范化,变得陈旧。相反,请考虑在报告生成期间使用它。否则,如前所述,您可能会遇到问题。

drop table if exists person;
create table person
(   personId int auto_increment primary key,
    name varchar(100) not null,
    totSales decimal(9,2) not null,
    totComm decimal(9,2)
);
insert person(name,totSales,totComm) values
('Joe',0,0),
('Sally',0,0);
-- just added persons 1 and 2 (auto_inc)

drop table if exists sale;
create table sale
(   saleId int auto_increment primary key,
    saleDate date not null,
    personId int not null,
    sale decimal(9,2) not null,
    commission decimal(9,2) not null,
    index(personId), -- facilitate a snappier "group by" later
    foreign key (personId) references person(personId) -- Ref Integrity
);

insert sale(saleDate,personId,sale,commission) values
('2016-05-01',2,10,1),
('2016-05-01',1,40,4),
('2016-05-02',1,30,3),
('2016-05-07',2,10,1),
('2016-05-07',2,90,9);

-- the following dies on referential integrity, FK, error 1452 as expected
insert sale(saleDate,personId,sale,commission) values ('2016-05-01',4,10,1);

更新语句

update person p 
join  
(   select personId,sum(sale) totSales, sum(commission) totComm 
    from sale 
    group by personId 
) xDerived 
on xDerived.personId=p.personId 
set p.totSales=xDerived.totSales,p.totComm=xDerived.totComm;

结果

select * from person;
+----------+-------+----------+---------+
| personId | name  | totSales | totComm |
+----------+-------+----------+---------+
|        1 | Joe   |    70.00 |    7.00 |
|        2 | Sally |   110.00 |   11.00 |
+----------+-------+----------+---------+
2 rows in set (0.00 sec)

xDerived 只是一个别名。所有派生表都需要一个别名,无论您是否明确使用别名。

关于mysql - 根据对另一个表的选择结果更新表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37573424/

相关文章:

mysql - 为什么此查询返回空行

java - 如何让过时的应用程序版本显示一个对话框,表明有更新可用?

android - 为什么安卓模拟器不能用

php - 使用变量表和更多参数从 php 调用 mysql 存储过程

mysql - Mysql的列索引可以单独保存吗?

c# - 如何使用Elastic low-level-client批量插入嵌套类型对象?

java - 如何使用hibernate hql从表中批量删除记录?

performance - 在 PostgreSQL 中填充数据库

mysql - 根据第二个表中输入的值更新 MYSQL 表

windows-8 - "Visual Studio Extensions for Windows Library for Javascript"不会更新