sql查询逻辑最佳方法

juzqafwq  于 2021-06-29  发布在  Hive
关注(0)|答案(1)|浏览(391)

我在寻找我的两个查询获得的数据加上任何其他数据从驱动表。我使用以下代码,但有一种感觉,我的结果是错误的。

select * from(
select * from tbl_a a  
inner join tbl_b b on (a.id = b.id and a.col_a = b.col_b and a.col_c = '1')

union all

select * from tbl_a a  
inner join tbl_b b on (a.col_a = b.col_b and a.col_c = '1')
where (1=1)
and a.id <> b.id
and a.start_time <= b.u_start_time
and a.end_time >= b.u_end_time

union all

select * from tbl_a a  
where a.another_id 
NOT IN ( -- either query above)

) results;

我只是想知道这是否有意义,或者我怎么可能简化一些。。。

inn6fuwd

inn6fuwd1#

这里是前两个并集的查询,不清楚第三个并集条件是什么

SELECT * 
FROM
tbl_a a 
left join tbl_b b on b.id = a.id and b.col_b = a.col_a
left join tbl_b b1 on a.col_a= b1.col_b and a.id<>b1.id and a.start_time<=b1.u_start_time and a.end_time>=b1.u_end_time
WHERE
a.col_c=1
and COALESCE(b.id,b1.id) is not null

相关问题