Mysql Union All&按

时间:2017-06-07 21:21:23

标签: mysql

我有3张桌子

表成员

id   |   type
1    |    A
2    |    B
3    |    A

表佣金A

id   |  member_id   |     date     |   amount   |
1    |     1        |  2017-06-06  |   30.00    |
2    |     2        |  2017-06-18  |   20.00    |
3    |     1        |  2017-06-21  |   10.00    |
4    |     3        |  2017-06-23  |   30.00    |
5    |     3        |  2017-06-27  |   30.00    |
表委员会B

id   |  member_id   |     date     |   amount   |
1    |     2        |  2017-06-05  |   30.00    |
2    |     2        |  2017-06-13  |   30.00    |
3    |     1        |  2017-06-22  |   30.00    |
4    |     3        |  2017-06-22  |   30.00    |
5    |     1        |  2017-06-23  |   30.00    |

我希望结果只显示成员类型A,并按日期排序

id  |     date       |   member id   |    from
1   |   2017-06-06   |      1        |   table A
3   |   2017-06-21   |      1        |   table A
3   |   2017-06-22   |      1        |   table B
4   |   2017-06-22   |      3        |   table B
5   |   2017-06-23   |      1        |   table B

且总金额= 130

我试过了:

select member_id, date, amount 
from commission A 
union all 
select member_id, date, amount 
from commission B 
order by date asc

但我不能只选择A类成员:我的查询显示所有成员'结果

我该怎么做?

1 个答案:

答案 0 :(得分:0)

您需要加入members表格才能过滤类型:

select      c.*
from        member m
inner join (
            select id, member_id, `date`, amount, 'table A' `from`
            from   commissionA
            union all
            select id, member_id, `date`, amount, 'table B' `from`
            from   commissionB
           ) c
        on  m.id = c.member_id
where       m.type = 'A'
order by    c.`date` asc

注意:我会避免像datefrom这样的名字,因为它们有特殊含义。

要获取额外行中的总计,请按所有字段(金额除外)进行分组,然后添加with rollup子句。最后,过滤掉生成的任何小计:

select *
from   (
    select      c.id, c.member_id, c.`date`, sum(c.amount) amount, c.`from`
    from        member m
    inner join (
                select id, member_id, `date`, amount, 'table A' `from`
                from   commissionA
                union all
                select id, member_id, `date`, amount, 'table B' `from`
                from   commissionB
               ) c
            on  m.id = c.member_id
    where       m.type = 'A'
    group by    c.id, c.member_id, c.`date`, c.`from` with rollup) base
where       id is null or `from` is not null;
order by    `date` asc