mysql - 在没有外键的情况下对来自不同表的两个不同列进行求和和差分

时间:2016-04-02 20:32:25

标签: mysql

我有一张预算表

budget_cost, p_id

然后工作包表,它有

milewp_cost, p_id

两者都是p_id的外键如果我只是总结它们,我怎么能区别? 我正在研究这段代码,但没有运气。

select sum(b.milewp_cost) as a, sum(a.budget_cost)b, (a-b) as c

编辑
select * from t_budget

t_budget
_________________________
budget_id   budget_amount
1           500
2           600

select * from t_milewp

t_milewp
_________________________
milewp_id   milewp_amount
1           100
2           300

select SUM(budget_amount) as ww from t_budget

ww
__
1100

select SUM(milewp_amount) as ee from t_milewp

ee
__
400

从最后两个查询。我如何加入并减去它们?没关系p_id,因为我将使用where条款

2 个答案:

答案 0 :(得分:0)

我认为你想要实现的目标并不清楚,所以我会按照我的假设去做。

MySQL没有FULL JOIN,但您可以LEFT JOINRIGHT JOIN模拟它。

示例数据:

CREATE TABLE t_budget (budget_id int, budget_amount int);
CREATE TABLE t_milewp (milewp_id int, milewp_amount int);

INSERT INTO t_budget VALUES (1, 500), (2, 600);
INSERT INTO t_milewp VALUES (1, 100), (2, 300);

查询(对于整个表格):

SELECT SUM(budget_amount) - SUM(milewp_amount)
FROM (
  SELECT tb.budget_id, tm.milewp_id, tb.budget_amount, tm.milewp_amount
  FROM t_budget tb
  LEFT JOIN t_milewp tm
    ON tb.budget_id = tm.milewp_id
  -- add WHERE here if needed (on tb.budget_id)
  UNION 
  SELECT tb.budget_id, tm.milewp_id, tb.budget_amount, tm.milewp_amount
  FROM t_budget tb
  RIGHT JOIN t_milewp tm
    ON tb.budget_id = tm.milewp_id
  -- add WHERE here if needed (on tm.milewp_id)
  ) foo

输出:

700

如果您需要限制计算ID,请在我发表评论的位置添加WHERE子句

这是 SQL Fiddle

答案 1 :(得分:0)

以下是如何将两个查询与select子句中的子查询组合在一起:

select 
  (select sum(budget_amount) from t_budget)
  -
  (select sum(milewp_amount) from t_milewp)
;

以下是另一种在join子句中使用子查询实现相同的方法:

select b.amount - m.amount
from       (select sum(budget_amount) as amount from t_budget) b
cross join (select sum(milewp_amount) as amount from t_milewp) m;

如果你想要每个p_id的结果:

select b.p_id, b.amount - m.amount
from (select p_id, sum(budget_amount) as amount from t_budget group by p_id) b
join (select p_ad, sum(milewp_amount) as amount from t_milewp group by p_id) m
  on m.p_id = b.p_id;

但这只适用于每个p_id在两个表中都有一个条目的情况。否则你需要适当的外连接 - 也许是一个完整的外连接,即使你没有必要模拟,因为MySQL不具备它。