不要使用mysql从两个表中选择数据

时间:2014-08-21 07:57:55

标签: mysql

我有3张桌子的销售和收据以及顾客。我的表和结果表是

促销

date          total     sale_type    cust_id
15-8-2014      50       credit       1
16-8-2014      100      credit       1
17-8-201       200      return       1
18-8-2014      300      return       1

收据

date           net_amount           cust_id
15-8-2014          100                  1
16-8-2014          200                  1
17-8-2014          300                  1

客户

id name

1 222

结果

date            total    net_amount
15-8-2014       50       100
16-8-2014      100       200
17-8-2014      200       300
18-8-2014      300 

我的查询得到了这些结果,但我希望在sale_type ='credit'和sale_type ='return'的情况下从销售表中得到总和。

我的查询是

select date,total,net_amount 
from (select customer.name as customer_name,
             customer.reseller_name as reseller_name,
             sale.date as date, 
             sale.total as total, 
             null as net_amount, 
             2 as sort_col 
      from sale 
        inner join customer 
          on customer.id=sale.cust_id 
      union all 
      select customer.name customer_name,
             customer.reseller_name as reseller_name,
             receipt.date as date, 
             null as total, 
             receipt.net_amount as net_amount, 
             1 as sort_col
      from receipt 
        inner join customer 
          on customer.id=receipt.cust_id) as a 
order by date desc, sort_col desc

任何机构都可以提供任何解决方案吗?

1 个答案:

答案 0 :(得分:0)

听起来你只想要一个GROUP BY条款。此外,如果我理解正确,我认为您可以使用UNION摆脱NULLLEFT JOIN业务:

SELECT S.date, 
       S.total, 
       R.net_amount, 
       SumTable.group_total
FROM sale AS S
  LEFT JOIN  receipt AS R 
    ON S.date = R.date
  JOIN (SELECT sale_type, 
               SUM(total) AS group_total 
        FROM sale 
        GROUP BY sale_type) AS SumTable 
    ON S.sale_type = SumTable.sale_type

以下是显示结果的sqlfiddle

DATE        TOTAL   NET_AMOUNT  GROUP_TOTAL
-------------------------------------------
15-8-2014   50      100         150
16-8-2014   100     200         150
17-8-2014   200     300         500
18-8-2014   300     (null)      500