Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a complex SQL MINUS query with LEFT OUTER JOIN equivalent

Tags:

sql

outer-join

Trying to figure how how to replace the following, with equivalent left outer join:

select distinct(a.some_value)
from table_a a, table_b b
where a.id = b.a_id 
and b.some_id = 123
and b.create_date < '2014-01-01' 
and b.create_date >= '2013-12-01'  
MINUS
select distinct(a.some_value)
from table_a a, table_b b
where a.id = b.a_id 
and b.some_id = 123 
and b.create_date < '2013-12-01' 

Can not do "NOT IN", as the second query has too much data.

like image 767
Dmitry Grinberg Avatar asked Jan 09 '14 00:01

Dmitry Grinberg


Video Answer


1 Answers

SELECT * FROM
(
  select distinct(a.some_value)
  from table_a a, table_b b
  where a.id = b.a_id 
  and b.some_id = 123
  and b.create_date < '2014-01-01' 
  and b.create_date >= '2013-12-01'  
) x
LEFT JOIN 
(
  select distinct(a.some_value)
  from table_a a, table_b b
  where a.id = b.a_id 
  and b.some_id = 123 
  and b.create_date < '2013-12-01'
) y
ON 
  x.some_value = y.some_value
WHERE 
  y.some_value IS NULL
like image 61
Xiangpeng Zhao Avatar answered Sep 18 '22 01:09

Xiangpeng Zhao