两表关联,查询一张表数据是否在另外一张表中也有,并且这部分数据标红排序


老大给了我一个需求,有两张表,一张表示预警结果表cims_warn_result,另一张是企业监控表cims_warn_monitor,我要做一个列表展示预警结果表的信息,

但是如果cims_warn_result表的企业在cims_warn_monitor表中存在的话,那么我要把一整条数据标红,并且排序


实现思路:


第一种方法

1)写一条sql,查询哪些企业在cims_warn_result表中存在,并且也在cims_warn_monitor表中,实现方法用exist

select * from cims_warn_result result where exist (select 'x' from cims_warn_monitor mon where mon.企业代码 = result.企业代码)

然后给一个列标识下这部分数据为1

2) 再写一条sql,查询哪些企业在cims_warn_result表中存在,但是不在cims_warn_monitor表中,实现方法用 not exist

select * from cims_warn_result result where not  exist (select 'x' from cims_warn_monitor mon where mon.企业代码 = result.企业代码)

然后给一个列标识下这部分数据为2

最后两表关联,union all

这样就可以得到数据1为监控的企业,2是未监控的企业


第二种方法

直接预警结果表cims_warn_result与企业监控表cims_warn_monitor关联,但是中间用cims_warn_monitor表的uuid判断,如果为空,那么给这个列标识为2,如果不为空,

标识为1,用case when来实现,代码如下:

case when b.uuid is null THEN 2 else 1 end as mon
最后order by mon asc就可以了


第二种方法最佳,代码量很少,第一种方法不推荐,因为代码量太大,看上去太复杂


怕忘记,所以做下笔记


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值