MySQL连接查询具有多个where条件

时间:2014-12-31 05:47:01

标签: mysql sql select join sum

我有3张桌子。我需要加入这3个并从每个表中获取2个字段。并且几乎没有条件。条件是日期范围。即使一个表具有结果,我也需要将其与显示为0的其他表数据一起显示。 我尝试过使用内连接。但是它所做的只是在第一个条件下,如果没有结果,它首先不会用于下一个条件。我的表格结构和所需的输出如下所示。

表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 |
+--------+---------+------------+

输出:2014年12月1日至2014年12月31日之间的总金额

+---------+---------------+---------------+---------------+-------+
| 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

1 个答案:

答案 0 :(得分:1)

试试这个:

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;