简体   繁体   中英

Mysql sum column from multiple table in the same id

I have 18 table in mysql.

All of tables have a column Result (ex a.result, b.result etc..) I need to select the result of 18 table and sum together for all of the id.

d.id 1 = a.result + b.result + c.result (of id 1 in all of the table)

Thanks

Use UNION ALL to get all value from all 18 tables. Then use SUM function.

Query

SELECT SUM(t.result) FROM(
    SELECT result FROM table_1
    UNION ALL
    SELECT result FROM table_2
    UNION ALL
    ...........................
    ...........................
    SELECT result FROM table_18
)t;

If you want the result column value for specific id's from the table. Then, use WHERE .

It's not pretty, but something like this would work

SELECT a.result + b.result + c.result -- (All the way to r.result...)
FROM TableA a
INNER JOIN TableB b
  ON a.ID = b.ID
INNER JOIN TableC c
  ON b.ID = c.ID
-- (All the way to TableR ...)

You might want to consider using OUTER JOINS unless you're absolutely certain that the ID will always exist in all tables.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM