I have two tables, Table A and Table B that look something like this:
Table A structure: id | name | statistic1 | statistic2
Table B structure: id | name | datetime | round_info | statistic1 | statistic2
Basically, Table B records statistic1 and statistic2 for many different rounds, so there will be many unique entries with the same name, and I want Table A to be a master list where each name in B is represented as one row in A, where statistic1 and statistic2 in A are the sum of statistic1 and statistic2 for each round in B, respectively.
The script I need for this should get each name from Table B, check if it's in A, if it isn't, insert a default row with that name, then update it with the table B data, and if it is in A already, simply call an update on it as well.
I have this code which has some drawbacks:
UPDATE A
INNER JOIN (SELECT B.name, sum(statistic1) as s1, sum(statistic2) as s2
FROM B
group by name) as t ON A.name = t.name
SET A.statistic1 = t.s1;
It doesn't insert rows to A when a name in B is not in A, and it only updates one of the statistics at a time.
Have you tried this:
UPDATE A
SET A.statistic1 = (SELECT sum(B.statistic1)
FROM B
WHERE B.name = A.name
group by B.name )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.