将union和sum与不同的视图列相结合

时间:2016-07-27 05:06:34

标签: mysql union sql-view

My

我在这里查看

我想要尝试的是使select o.id_project AS id_project, sum((o.office_expense + m.misc_expense)) AS total_expense from v_office_project o inner join v_misc_project m on o.id_project = m.id_project group by o.id_project, m.id_project 看起来像那样。 我试过这段代码

v_misc_project.id_project

我知道我的代码不会打印select o.id_project AS id_project from v_office_project o union select m.id_project as id_project, sum((o.office_expense + m.misc_expense)) AS total_expense from v_office_project o inner join v_misc_project m on o.id_project = m.id_project group by id_project 。所以我尝试联盟打印两个id_project,并得到错误不同数量的列。

var_export

那么,还有另一种方法吗? 提前谢谢,

1 个答案:

答案 0 :(得分:1)

SELECT
    o.id_project AS id_project,
    sum(
        o.office_expense + ifnull(m.misc_expense, 0)
    ) AS total_expense
FROM
    v_office_project o
LEFT JOIN v_misc_project m ON o.id_project = m.id_project
GROUP BY
    id_project
UNION
    SELECT
        m.id_project AS id_project,
        sum(
            ifnull(o.office_expense, 0) + m.misc_expense
        ) AS total_expense
    FROM
        v_office_project o
    RIGHT JOIN v_misc_project m ON o.id_project = m.id_project
    GROUP BY
        id_project

在工会的第一个选择中,您缺少费用字段。

此外,连接失踪了,添加了它。而不是INNER JOIN使用LEFTRIGHT Join,否则您只能获得两个表中id_project的结果。

在计算中添加了ifnull(),因为LEFT / RIGHT联接可以返回null,必须将其视为0。