简体   繁体   English

来自同一ID的多个表的MySQL sum列

[英]Mysql sum column from multiple table in the same id

I have 18 table in mysql. 我在mysql中有18个表。

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. 所有表都有一列结果(例如a.result,b.result等。)我需要选择18个表的结果,并对所有id求和。

d.id 1 = a.result + b.result + c.result (of id 1 in all of the table) d.id 1 = a.result + b.result + c.result (所有表中的id为1)

Thanks 谢谢

Use UNION ALL to get all value from all 18 tables. 使用UNION ALL从所有18个表中获取所有值。 Then use SUM function. 然后使用SUM函数。

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. 如果要从表中获取特定ID的result列值。 Then, use WHERE . 然后,使用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. 除非您绝对确定ID将始终存在于所有表中,否则您可能要考虑使用OUTER JOINS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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