MySql 3表,嵌套连接

时间:2016-02-09 17:41:50

标签: 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

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

1 个答案:

答案 0 :(得分:0)

尝试使用" 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