![](/img/trans.png)
[英]how do i join 7 tables where a column (which exists in all tables) equals the same content in all tables?
[英]How do I JOIN multiple tables where some, not all, columns are the same and return the sum of each column?
我有多個表來跟蹤來自不同位置(即冷與暖)的信息,這些信息根據季節提供服務,並且需要創建位置的公司級別視圖。
查看 UNIONS 和 JOINS 的描述,看起來這些表必須具有相同數量的列或相同的列名。 我需要的是使用 PHP MySQL 提供相同列的總和以及唯一列的總和的結果。
Table1 +-------+-------+-------+ | col-A | col-B | col-C | +-------+-------+-------+ | 2 | 8 | 5 | +-------+-------+-------+ | 1 | 9 | 7 | +-------+-------+-------+ | 3 | 2 | 3 | +-------+-------+-------+ Table2 +-------+-------+-------+ | col-1 | col-2 | col-3 | +-------+-------+-------+ | 2 | 1 | 6 | +-------+-------+-------+ | 5 | 5 | 4 | +-------+-------+-------+ | 2 | 7 | 3 | +-------+-------+-------+ Table3 +-------+-------+-------+-------+-------+-------+ | col-A | col-B | col-1 | col-2 | col-3 | col-4 | +-------+-------+-------+-------+-------+-------+ | 9 | 4 | 1 | 2 | 1 | 4 | +-------+-------+-------+-------+-------+-------+ | 2 | 6 | 6 | 8 | 3 | 6 | +-------+-------+-------+-------+-------+-------+ | 4 | 7 | 3 | 2 | 4 | 5 | +-------+-------+-------+-------+-------+-------+ Result Table +-------+-------+-------+-------+-------+-------+-------+ | col-A | col-B | col-C | col-1 | col-2 | col-3 | col-4 | +-------+-------+-------+-------+-------+-------+-------+ | 21 | 36 | 15 | 19 | 25 | 21 | 15 | +-------+-------+-------+-------+-------+-------+-------+
我認為這可以通過UNION
來完成,如下所示:
SELECT SUM(`col-A`) AS 'Col-A',SUM(`col-b`) AS 'Col-B',
SUM(`col-C`) AS 'Col-C',SUM(`col-1`) AS 'Col-1',
SUM(`col-2`) AS 'Col-2',SUM(`col-3`) AS 'Col-3',SUM(`col-4`) AS 'Col-4'
FROM
(SELECT `col-A`,`col-b`,0 AS 'col-c',`col-1`,`col-2`,`col-3`,`col-4` FROM table_3 UNION
SELECT 0,0,0,`col-1`,`col-2`,`col-3`,0 FROM table_2 UNION
SELECT `col-A`,`col-b`,`col-C`, 0,0,0,0 FROM table_1 ) XX
因為 table_3 的列最多,所以我把它放在聯合的頂部。 以下查詢只需要在表中不存在該列的情況下填充0
(零)即可滿足聯合要求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.