大数据=SQL Boy,SQL Debug打破SQL Boy 的僵局

网上经常盛传 大数据=sql boy,后端开发=crud boy,算法工程师=调参boy

在大数据领域也工作了好几年了,确实大数据开发,很多工作就是写sql,hive sql、spark sql、flink sql等等sql

一、背景:

但是经常有这样一个需求,一大段sql 跑出来之后,发现不是自己想要的结果?比如:

demo 1:
select id,name from (
select id,name from table1
union all
select id,name from table2
union all
select id,name from table3
union all
select id,name from table4
)t group by id,name

demo 2:
select a.id,a.name,a.class from (select id,name from table1 where id>=10) a left join (select name,class from table2 where name is not null)
 b on a.name=b.name;

比如说:

demo 1 中的sql 出来这样的结果数据

idname
101xiaolan
102xiaobing
100xiaohong

但是其中id为100的这条数据从业务逻辑上来看应该是被过滤掉的,但是实际却出来了,也就是代码实际运行结果和我们预期想的不一样

其实和c语言开发和java 开发类似,就是预期结果和代码实际结果不一致,一般在java开发或者c语言开发中,我们是通过打日志(print、log.debug )或者使用idea打断点进调试模式进行调试代码,一步一步查看中间结果,也称之为debug过程。

那么因此想到sql 实际运行结果和预期不符的时候能不能进行debug 调试呢?

二、大部分人的解决方案:

大部分数据开发者遇到这个问题,都是把sql 进行拆分,比如说demo 1 的sql拆分如下4个sql,分别对每个sql 进行运行判断100这个结果到底是哪个表产出的。

select id,name from table1 where id='100'

select id,name from table2 where id='100'

select id,name from table3 where id='100'

select id,name from table4 where id='100'

或者稍微修改一下

select * from (
select id,name,flag from (
select id,name,'1' as flag from table1
union all
select id,name,'2' as flag from table2
union all
select id,name,'3' as flag from table3
union all
select id,name,'4' as flag from table4
)t group by id,name,flag )t1 where id='100'

三、最终方案:

那有没有一种方法,也能做到像和java或者c语言一样进行调试中间结果呢,也就是idea debug或者通过打印日志的方式?因此称呼sql 调试的过程为sql debug。

java 或者c 语言 开启debug 模式,需要打印日志或者配合idea 进行debug,本文先讲述怎么通过打印日志进行sql debug。

(1)开启debug 模式

(2)拆分sql

(3)输出中间结果

(4)人工判断中间结果是否正确定位原因

(5)重复2-4过程直到找到最终结果结束

举例:

select u,
       max(tm),
       p1
from
  (
   select device_id as u,unix_timestamp(dt,'yyyy-MM-dd')*1000 as tm,p1
        from test.table1
        where dt='2023-04-09' and length(trim(device_id))>0
        union ALL
        select device_id as u,unix_timestamp(dt,'yyyy-MM-dd')*1000 as tm,p1
        from test.table2
        where dt='2023-04-09' and length(trim(device_id))>0	 
    union all 
     select device_id as u,unix_timestamp(dt,'yyyy-MM-dd')*1000 as tm,p1
     from test.table3
    where dt='2023-04-09' and length(trim(device_id))>0
    
  ) a
GROUP BY u,
         p1

(1)将这样一段sql 进行转换成语法树(如下图),这样就完成了sql解析和拆分(实际上更复杂的sql 也可进行快速拆分)

(2)将拆分出来的sql进行批量建表

(3)实际分析问题的时候,可以直接查询建的中间表数据

(4)分析完成之后需要自动删除建的中间表数据

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

诸葛子房_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值