我有 3 个表。我需要加入这 3 个并从每个表中获取 2 个字段。而且 where 条件很少。其中条件是日期范围。即使一个表有结果,我也需要将其与显示为 0 的其他表数据一起显示。 我试过使用内部连接。但它所做的只是采用第一个 where 条件,如果第一个没有结果,它将不会进入下一个条件。我的表结构和所需的输出如下所示。
表1
+--------+---------+------------+
| amount | site_id | date |
+--------+---------+------------+
| 10 | 1 | 12/12/2014 |
| 50 | 2 | 10/12/2014 |
| 30 | 3 | 05/11/2014 |
+--------+---------+------------+
表2
+--------+---------+------------+
| amount | site_id | date |
+--------+---------+------------+
| 100 | 1 | 2/11/2014 |
| 40 | 2 | 10/10/2014 |
| 30 | 3 | 05/11/2014 |
+--------+---------+------------+
表3
+--------+---------+------------+
| amount | site_id | date |
+--------+---------+------------+
| 60 | 1 | 12/12/2014 |
| 50 | 3 | 11/12/2014 |
| 70 | 4 | 05/09/2014 |
+--------+---------+------------+
输出:01/12/2014 和 31/12/2014 之间的总量
+---------+---------------+---------------+---------------+-------+
| site_id | table1_amount | table2_amount | table3_amount | total |
+---------+---------------+---------------+---------------+-------+
| 1 | 60 | 0 | 60 | 120|
| 3 | 0 | 0 | 50 | 50 |
+---------+---------------+---------------+---------------+-------+
任何人都可以建议查询以获得此输出吗? 这是我到目前为止所做的
select sum(table1.amount),sum(table2.amount),sum(table3.amount),(sum(table1.amount)+sum(table2.amount)+sum(table3.amount)) from table1 inner join table2 on table1.site_id=table2.site_id inner join table3 on table3.site_id=table2.site_id where table1.date>='01/12/2014' and table1.date<='31/12/2014' or table2.date>='01/12/2014' and table2.date<='31/12/2014' or table3.date>='01/12/2014' and table3.date<='31/12/2014' group by table1.site_id
最佳答案
试试这个:
SELECT S.site_id,
IFNULL(t1.table1_Amount, 0) AS table1_Amount,
IFNULL(t2.table2_Amount, 0) AS table2_Amount,
IFNULL(t3.table3_Amount, 0) AS table3_Amount,
(IFNULL(t1.table1_Amount, 0) + IFNULL(t2.table2_Amount, 0) + IFNULL(t3.table3_Amount, 0)) AS total
FROM Site S
LEFT OUTER JOIN ( SELECT t1.site_id, SUM(t1.amount) AS table1_Amount
FROM table1 t1
WHERE t1.date >= '01/12/2014' AND t1.date <= '31/12/2014'
GROUP BY t1.site_id
) AS t1 ON S.site_id = t1.site_id
LEFT OUTER JOIN ( SELECT t2.site_id, SUM(t2.amount) AS table2_Amount
FROM table2 t2
WHERE t2.date >= '01/12/2014' AND t2.date <= '31/12/2014'
GROUP BY t2.site_id
) AS t2 ON S.site_id = t2.site_id
LEFT OUTER JOIN ( SELECT t3.site_id, SUM(t3.amount) AS table3_Amount
FROM table1 t3
WHERE t3.date >= '01/12/2014' AND t3.date <= '31/12/2014'
GROUP BY t3.site_id
) AS t3 ON S.site_id = t3.site_id;
关于具有多个where条件的MySQL连接查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27716717/