Oracle左连表查询案例

场景:有两张表,一张异常信息表,一张异常处理信息表,根据用户名查询该用户可以看到的异常信息,同时还要连表查询异常信息表里的改进方案和备注数据;

SQL1:

select b.*,h.* from usm_exception_bill b 
left join usm_exception_handling h on b.code=h.code
where b.is_delete=0 and b.is_active=0
and h.is_delete=0 and h.is_active=0
and b.username='admin';

描述:上面情况只会查询出USM_EXCEPTION_BILL表和USM_EXCEPTION_HANDLING表都满足条件的表,但是当USM_EXCEPTION_HANDLING表没有USM_EXCEPTION_BILL表的处理信息时,只会

查询出USM_EXCEPTION_BILL和USM_EXCEPTION_HANDLING都有的数据,那么在处理表没有处理信息的异常数据就不会被查询出来,客户看到的数据就是不完整的;

SQL2:

select b.*, h.* from usm_execption_bill 
left join usm_exception_handling h on h.code=b.code
and b.is_delete=0 and b.is_active=0 
and h.is_delete=0 and h.is_active=0 
and b.username='admin';

描述:这样可以查询出USM_EXCEPTION_BILL表和USM_EXCEPTION_HANDLING表有关联的全部数据,但是条件就不生效了,成了摆设;

SQL3:

select b.*, h.* from 
(select * from usm_exception_bill 
where is_delete=0 and is_active=0 and b.username='admin') b
left join usm_exception_handling h on b.code = h.code
and b.is_delete=0 and b.is_active=0
and h.is_delete=0 and h.is_active=0;

描述:先去USM_EXCEPTION_BILL表把满足条件的数据查询出来,在去USM_EXCEPTION_HANDLING表匹配出相应的处理信息,这样既不会数据显示不全,也不会过滤条件失效;

原文地址:https://www.cnblogs.com/mxh-java/p/14577676.html