加入MySql表和SUM

时间:2014-12-10 09:54:25

标签: php mysql sql join union

我试图用3个表编写JOIN Query。我需要Query来返回每个基于用户传递给查询的链接值的总和。在表格结构下面添加了所需的结果和我尝试过的查询。

表1:UserDetails


|   ID    | Name    | Link    |   
|   1     | User A  |    12   |
|   2     | User B  |    12   |
|   3     | User C  |    12   |

表2:保存


|CreatedBy| Amount  |
|   3     | 100     | 
|   3     | 50      | 
|   2     | 75      | 

表3:费用


|CreatedBy| Amount  |
|   2     | 20      | 
|   1     | 15      | 
|   3     | 85      | 

通过将链接值传递给查询,必须为每个用户返回总计(节省+费用)。

结果1 :如果传递链接值12。

查询结果


|User Name| Total   |
|User A   | 15      | 
|User C   | 235     | 

结果2 :如果传递链接值11。

查询结果


|User Name| Total   |
|User B   | 95      | 

以下查询未返回任何结果。

SELECT 
    t1.name, 
    SUM(t2.total_amount+t3.total_amount) 
FROM 
    userdetails t1 
        LEFT JOIN savings t2 
            ON t2.created_by=t1.id 
        LEFT JOIN expense t3 
            ON t3.created_by=t1.id 
WHERE 
    t1.link=12 
    AND t1.status=1 
    AND t2.status=2 
    AND t3.status=2 
GROUP BY 
    t2.created_by,
    t3.created_by

3 个答案:

答案 0 :(得分:0)

进行外连接时,不能在where子句中放置条件,否则会使外连接无效并将其转换为正常的内连接。然而,您可以通过将条件添加到连接中来获得您想要的内容(基于您的where子句):

SELECT 
    t1.name, 
    SUM(t2.total_amount+t3.total_amount) 
FROM 
    userdetails t1 
        LEFT JOIN savings t2 
            ON t2.created_by=t1.id 
            AND t2.status=2 
        LEFT JOIN expense t3 
            ON t3.created_by=t1.id 
            AND t3.status=2 
WHERE 
    t1.link=12 
    AND t1.status=1 
GROUP BY 
    t2.created_by,
    t3.created_by

您通常也不希望按照select子句中未命名的字段进行分组:

SELECT 
    t1.name, 
    SUM(t2.total_amount+t3.total_amount) 
FROM 
    userdetails t1 
        LEFT JOIN savings t2 
            ON t2.created_by=t1.id 
            AND t2.status=2 
        LEFT JOIN expense t3 
            ON t3.created_by=t1.id 
            AND t3.status=2 
WHERE 
    t1.link=12 
    AND t1.status=1 
GROUP BY 
    t1.name

答案 1 :(得分:0)

select 
    u.Name,
    u.link,
    c.total
from user_details u,
(select 
    "created by",
    sum(amount) Total
from 
    (select 
        "created by",
        amount
    from expense
    union all
    select 
        "created by",
        amount
    from savings)
    group by "created by") c
where u.ID=c."created by"
and  u.link=12;

答案 2 :(得分:0)

试试这个:

SELECT A.Name,A.link,B.total
FROM user_details A,
  (SELECT 'created by', SUM(amount) AS Total
  FROM
    (SELECT 'created by',amount
    FROM expense
    UNION ALL
    SELECT'created by',amount
    FROM savings)
  GROUP BY 'created by') B
WHERE A.ID=B.'created by'
AND A.link=12;

您可以field_name使用'Field Name''Column Title'将其显示在结果中。 确保表格中有一列created by