2016-05-16 67 views
0

我是通过我的两个查询获得的数据加上驱动表中的任何其他数据。我使用下面的代码,但感觉我的结果是错误的。查询逻辑最佳方法

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; 

我只是想知道,如果这是有道理,还是我怎么可能简化了一些这...

+0

你可以在SQLFiddle上创建示例数据库吗?并赞赏每个查询的一点点解释。 – Jigar

回答

0

这里是第2个工会查询,目前尚不清楚是什么第三个联合条件

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