【问题标题】:MYSQL left join missing out rowsMYSQL 左连接丢失了行
【发布时间】:2021-12-16 16:56:24
【问题描述】:

我有 4 张桌子。

1st table has: date and revenue
2nd table has: date and cost
3rd table has: date and fees 
4th table has: date and others

我正在使用以下公式计算最终收入值:

final = revenue - (cost + fees + others)

为了执行此操作,我在对所有这 4 个表执行左外连接时使用了合并操作。由于左外层的连接顺序很重要,所以当没有收入或成本时,我会错过费用。 Join order is revenue => cost => fees => others tables on date.

如果收入/成本缺失但费用/其他存在,我如何在缺失日期显示这些缺失行?

【问题讨论】:

  • 请添加查询
  • 这4个表格中的任何一个都可能缺少某个确定的日期,是吗?

标签: mysql join left-join coalesce


【解决方案1】:

我认为你需要:

SELECT `date`,  COALESCE(t1.revenue, 0) 
              - COALESCE(t2.cost, 0) 
              - COALESCE(t3.fees, 0) 
              - COALESCE(t4.others, 0) final
FROM ( SELECT `date` FROM t1
       UNION 
       SELECT `date` FROM t2
       UNION 
       SELECT `date` FROM t3
       UNION 
       SELECT `date` FROM t4 ) dates
LEFT JOIN t1 USING (`date`)
LEFT JOIN t2 USING (`date`)
LEFT JOIN t3 USING (`date`)
LEFT JOIN t4 USING (`date`)

如果date 列在每个表中未定义为唯一(客户端检查还不够!)那么您必须添加 GROUP BY 并在每笔钱上使用 SUM() (?)输出表达式中的列。

【讨论】:

    猜你喜欢
    • 2020-05-10
    • 2016-08-04
    • 2020-09-28
    • 2013-12-11
    • 2013-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多