如何连接多个表和SUM值?

时间:2013-02-28 05:36:10

标签: php mysql codeigniter

我有以下表格(和示例值):

**table1**
data_id (1, 2)

**table2:**
data_id (1, 2, 1, 2)
month(01, 01, 02, 02)
data(10, 5, 11, 2)

**table3**
data_id (1, 2, 1, 2)
month(01, 01, 02, 02)
data(10, 5, 11, 2)

**table4**
data_id (1, 2, 1, 2)
month(01, 01, 02, 02)
data(10, 5, 11, 2)

所有表都通过“data_id”连接。我需要SUM数据字段和GROUP BY月。 表结果如下:

**result**
month(01, 02)
table2.data(15, 13)
table3.data(15, 13)
table4.data(15, 13)

获取结果表的SQL语句是什么?

1 个答案:

答案 0 :(得分:2)

尝试此查询 修改

SELECT t2.month, sum(t2.data), sum(t3.data), sum(t4.data)
FROM table1 t1, table2 t2, table3 t3, table4 t4
WHERE t1.data_id = t2.data_id AND t1.data_id = t3.data_id AND t1.data_id = t4.data_id
AND t2.month = t3.month AND t3.month = t4.month
GROUP BY t2.month;

它总结了月份数据字段的值

FIDDLE