2016-05-16 66 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