Mysql实现full join的替换方法
2015-08-24 18:19
721 查看
目前mysql还不支持full join,只能使用left join、union、right join来实现。但使用这个方法解决多次full join的话代码量非常庞大,一直在思考有没有其他替代方法。
今天解决一个问题的时候突然想到了一个替代方法:使用行列转换。
这个方法有一定的局限性,就是连接条件在2个连接表中最多只能有一条记录(不过大部分连接情况也就是连接条件在连接表中最多只有一条记录)。
下面是我具体实现的sql:
大致思路说下:2个被连接表增加一个标识字段,使用不同的值,之后将这2个表union all下,使用连接条件将union all的结果分组且使用行列转换。
今天解决一个问题的时候突然想到了一个替代方法:使用行列转换。
这个方法有一定的局限性,就是连接条件在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的结果分组且使用行列转换。
相关文章推荐
- mysql 通过bin-log恢复数据方法
- Mysql事务提交方式
- MYSQL 存储过程学习
- 每天进步一点点————MySQL锁
- 响影响MySQL性能的相关因素
- 如何设计高效合理的MySQL查询语句
- MYSQL的常用命令和增删改查语句和数据类型
- activemq与mysql持久化
- Mysql Cluster水平扩展-添加数据节点
- mysql 读写分离
- 【MySQL】frm文件解析
- MySQL的安装和使用
- 连接mysql数据库,忘记root密码
- 【其他】MySql常用命令
- 【其他】MySql数据库的安装与卸载
- MySQL简单MHA环境搭建
- MySQL主从复制
- MySql Cluster搭建
- jsp直接读取mysql数据库内容
- mySql 基本语法学习笔记