描述:
在MYSQL4.1版本之前的MYSQL数据库语法中,很悲剧的不支持子查询.所以,对于相对复杂一些的语句,一般通过拆分SQL语句为简单语句,也可以实现相关业务.但是考虑逻辑处理,处理复杂度等原因,希望能够找到一种替代方案.
解决:
可以通过使用left join inner jion right jion 左右内联连接来达到子查询对应的效果.在其他数据库中相应SQL语法也可以适用.考虑到数据库移植的问题,这种方案比较具有通用性.
示例:
采用子查询语句:
1 select a.level level,a.id id from cq_user a,
2 (select distinct id_target as id from e_money
3 where time_stamp between 1101310000 and 1102000000 and type in (6,8)) b
4 where a.id=b.id
2 (select distinct id_target as id from e_money
3 where time_stamp between 1101310000 and 1102000000 and type in (6,8)) b
4 where a.id=b.id
采用拆分SQL语句:
1 select distinct id_target as id from e_money where time_stamp between 1101310000 and 1102000000 and type in (6,8);
2 --从第一句获取id后,遍历获得id列表 1,2,3,4,5,6,7,8...
3 select level,id from cq_user where id in (1,2,3,4,5,6,7,8...);
2 --从第一句获取id后,遍历获得id列表 1,2,3,4,5,6,7,8...
3 select level,id from cq_user where id in (1,2,3,4,5,6,7,8...);
采用左连接语句:
1 select distinct a.level,a.id from cq_user a
2 left join e_money b
3 on a.id = b.id_target where b.type in (6,8) and b.time_stamp between 1101310000 and 1102000000
4 order by a.level
2 left join e_money b
3 on a.id = b.id_target where b.type in (6,8) and b.time_stamp between 1101310000 and 1102000000
4 order by a.level
这三个语句的执行结果相同.可以对比以上三种方式,拆分SQL,必须通过编程辅助来得到下一个SQL的条件,增加了程序复杂度.而采用左连接的语句,则无需附加编程就可以达到相同效果.
总结:
提供解决方案:
1.通过拆分SQL为简单语句实现,但是需要通过辅助编程,支出额外的编程量.
2.通过使用left join inner jion right jion 左右内联连接来达到子查询对应的效果,无需附加编程.