MySql 3 表,嵌套连接

标签 mysql join

Invoice
|    id   | invoice_date|
   123435   2016/02/09
   123436   2016/02/09
   123437   2016/02/09

Payments
|invoice_id| pmt_type| amount |
   123435       1       1000
   123435       2       2500
   123436       2       5000
   ...

Payments_legend
|type| description| 
   1      cash       
   2      check 
   3      credit 

我对这个感到头疼。我需要提取日常交易并认为这很简单。我遇到的问题是许多嵌套连接,除非有更简单的方法来做到这一点。从表面上看,它确实很简单。

下面给出了我需要的所有发票...

SELECT id AS Invoice FROM invoice WHERE DATE(invoice_date) = DATE(NOW())

但这就是我感到困惑的地方。我需要按发票分组的每个 payments.amount 列的总和,并为每个 payments.pmt_type 分成列。哎呀。

我需要的报告如下...

id  sum(pmt_type=1)  sum(pmt_type=2)  sum(pmt_type=3)

看起来像...

Invoice  Cash  Check  Credit
123435   1000  2500   0
123436   0     5000   0
123437   0     0      7500

如有任何帮助,我们将不胜感激。

感谢 NECULON 的帮助

SELECT invoice.id,
sum(if(payments.pmt_type = 1, payments.amount, 0)) AS Cash,
sum(if(payments.pmt_type = 2, payments.amount, 0)) AS Chek,
sum(if(payments.pmt_type = 3, payments.amount, 0)) AS Credit,
sum(if(payments.pmt_type = 9, payments.amount, 0)) AS Warranty,
sum(if(payments.pmt_type = 10, payments.amount, 0)) AS Paypal,
sum(if(payments.pmt_type = 7, payments.amount, 0)) AS Refund,
(sum(if(payments.pmt_type = 1, payments.amount, 0))+sum(if(payments.pmt_type = 2, payments.amount, 0))+sum(if(payments.pmt_type = 3, payments.amount, 0))+sum(if(payments.pmt_type = 9, payments.amount, 0))+sum(if(payments.pmt_type = 10, payments.amount, 0))-sum(if(payments.pmt_type = 7, payments.amount, 0))) AS Total
FROM invoice
JOIN payments ON invoice.id = payments.invoice_id
WHERE DATE(invoice_date) = DATE(now())
GROUP BY invoice.id WITH ROLLUP

这给了我我所需要的。再次感谢!

最佳答案

尽量使用“IF”或“CASE”。像这样:

select 
  invoice.id,
  sum(if(payments.pmt_type = 1, payments.amount, 0)) cash,
  sum(if(payments.pmt_type = 2, payments.amount, 0)) check,
  sum(if(payments.pmt_type = 3, payments.amount, 0)) credit
from invoice
  join payment on invoice.id = payments.invoice_id
where date(invoice_date) = date(now())
group by invoice.id

参见此处:http://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html#function_if

关于MySql 3 表,嵌套连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35298611/

相关文章:

MySQL 没有在子查询中使用 INDEX

python - 在 Queue.task_done() 之后运行多线程代码

php - 当表达到 10 行时,为这些行分配唯一 ID

MySQL 查询不对计算值进行排序

mysql - 左连接不起作用

php - MYSQL 多重计数和求和

mysql - 为什么这个 MySQL 语句中的 GROUP BY 子句不抛出错误?

MySQL 从其他表中更新字段并进行分组

PHP 时间戳自表连接

mysql - 需要执行 MySQL OUTER JOIN