1. 程式人生 > >Mysql實現full join的替換方法

Mysql實現full join的替換方法

目前mysql還不支援full join,只能使用left join、union、right join來實現。但使用這個方法解決多次full join的話程式碼量非常龐大,一直在思考有沒有其他替代方法。

今天解決一個問題的時候突然想到了一個替代方法:使用行列轉換。

這個方法有一定的侷限性,就是連線條件在2個連線表中最多隻能有一條記錄(不過大部分連線情況也就是連線條件在連線表中最多隻有一條記錄)。

下面是我具體實現的sql:

select
  b.the_day, max(if(b.type_id = 1, b.amount, 0)) purchase_amount, max(if(b.type_id = 1, b.interest, 0)) purchase_interest,
  max(if(b.type_id = 2, b.amount, 0)) withdrawal_amount, max(if(b.type_id = 2, b.interest, 0)) withdrawal_interest
from
  (select
    a.the_day, round(max(if(a.type_id = 1, a.money, 0))) amount, max(if(a.type_id = 2, a.money, 0)) interest, 1 type_id
  from
    (select
      date(pe.purchase_begin_time) the_day, sum(pe.amount) money, 1 type_id
    from
      purchase pe
    inner join product pt on pe.product_id = pt.product_id and pt.type_id = 9
    where pe.purchase_status_id = 4 and pe.purchase_begin_time < '2015-08-13 21:00:00'
    group by the_day
    union all
    select
      date(uci.creat_time) the_day, sum(uci.interest) money, 2 type_id
    from
      user_current_interest uci
    where uci.type = 'IN' and uci.creat_time < '2015-08-14'
    group by the_day
    ) a
  group by a.the_day
  union all
  select
    date(wd.withdrawal_begin_time) the_day, sum(wd.amount), sum(wd.profit), 2 type_id
  from
    withdrawal wd
  where wd.withdrawal_status_id in (4, 5) and wd.product_id = 0 and wd.withdrawal_begin_time < '2015-08-14'
  group by the_day
  ) b
group by b.the_day;

大致思路說下:2個被連線表增加一個標識欄位,使用不同的值,之後將這2個表union all下,使用連線條件將union all的結果分組且使用行列轉換。