将 3 个表与 UNION 连接到不同的列

Posted

技术标签:

【中文标题】将 3 个表与 UNION 连接到不同的列【英文标题】:joining 3 table with UNION with different columns 【发布时间】:2020-03-23 08:49:23 【问题描述】:

我正在尝试在我的 php CRM 脚本中显示收入和支出月份。它适用于 2 张桌子。但现在我想再将一张表的金额与费用数据结合起来。我不知道该怎么做。

这是我提取收入和费用数据的查询

SELECT
    YEAR(v.paid_date) AS Yr,
    MONTHNAME(v.paid_date) AS Month,
    SUM(IF(v.IncomeOrExpense = 'Income', v.paid_amount, 0)) AS Income,
    SUM(IF(v.IncomeOrExpense = 'Expense', v.paid_amount, 0)) AS Expense
FROM in_exp v
GROUP BY Yr, Month
ORDER BY Yr DESC, Month DESC

我为此创建了一个视图:

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `in_exp`  AS  select `r`.`invoice_id` AS `invoice_id`,`r`.`customer` AS `customer`,`r`.`paid_amount` AS `paid_amount`,`r`.`paid_date` AS `paid_date`,`r`.`comments` AS `comments`,`l`.`company` AS `company`,'Income' AS `IncomeOrExpense` from (`receipt` `r` join `leads` `l` on((`r`.`customer` = `l`.`id`))) union all select `p`.`invoice_id` AS `invoice_id`,`p`.`vendor` AS `vendor`,`p`.`paid_amount` AS `paid_amount`,`p`.`paid_date` AS `paid_date`,`p`.`comments` AS `comments`,`v`.`name` AS `name`,'Expense' AS `Expense` from (`payments` `p` join `vendor` `v` on((`p`.`vendor` = `v`.`id`))) union all select `e`.`eid` AS `eid`,`e`.`user` AS `user`,`e`.`paid_amount` AS `paid_amount`,`e`.`paid_date` AS `paid_date`,`e`.`comments` AS `comments`,`u`.`firstname` AS `firstname`,'Expense' AS `Expense` from (`expense_pay` `e` join `users` `u` on((`e`.`user` = `u`.`id`))) ;

现在我想添加SUM(IF(v.IncomeOrExpense = 'Expense', v.paid_amount, 0)) AS Expense 再加一张表(费用)金额,其中包含供应商和金额。

有人可以建议我如何实现这一目标吗?我无法更改费用表的表结构,因为它已经连接到如此多的查询和表。

【问题讨论】:

您为什么选择视图中未在最终查询中使用的大量列? 【参考方案1】:

假设 select 对第三个 union 正常工作,然后将文字 'expense' 更改为其他东西 'expenseV' 说并添加语句

SUM(IF(v.IncomeOrExpense = 'ExpenseV', v.paid_amount, 0)) AS Expense

到您的查询

【讨论】:

以上是关于将 3 个表与 UNION 连接到不同的列的主要内容,如果未能解决你的问题,请参考以下文章

MS Access sql将5个表与列中的奇怪字符分组

将源自不同表的两个 postgresql tsvector 字段连接到单个 postgresql 视图中,以启用联合全文搜索

多个表与一个具有更多列的表

将两个表与部分匹配连接到完全匹配

UNION ALL 不适用于不同的列

MySQL联合查询