0

How can i join two tables after filtering each table with some condition and on getting the result of filter, join both the results.

Tried code but showing syntax error

SELECT * 
FROM Table1 
WHERE flag1 = 0  
JOIN SELECT * 
     FROM TABLE2 
     where flag2 = 0 on Table1.email = TABLE2.email
Aditya Srivastava
  • 2,630
  • 2
  • 13
  • 23

4 Answers4

2

There may not be enough (RAM/cache) space to save your filtered results and then join them together. It can be slower than you expect.

*technically you can, but not that efficient.

SELECT * 
FROM (
    SELECT * FROM Table1 where flag1 = 0
) A
JOIN (
    SELECT * FROM TABLE2 where flag2 = 0
) B 
ON A.orderlist_email = B.email;

however, I'd recommend just join them first, and where everything later. MySQL (or whatever sql engine) will (usually) do a fine job optimizing it for you.

SELECT * 
FROM Table1
JOIN TABLE2 
ON A.orderlist_email = B.email
WHERE Table1.flag1 = 0 
AND TABLE2.flag2 = 0;
N.Xu
  • 131
  • 1
  • 7
2

Consider the two Select Statements as SUBQUERIES, and the results of these two subqueries as two different tables and then try joining.

SELECT * FROM 
(SELECT * FROM Table1 where flag1 = 0) Table1 
JOIN 
(SELECT * FROM TABLE2 where flag2 = 0) Table2 
on Table1.orderlist_email = TABLE2.email
Tom J Muthirenthi
  • 3,028
  • 7
  • 40
  • 60
0
SELECT *  
FROM Table1 as t1
join Table2 as t2 on t1.orderlist_email = t2.email
where flag1 = 0 
and flag2 = 0

Correct join will be like this.

Naveed Ramzan
  • 3,565
  • 3
  • 25
  • 30
0

Unless I'm missing something, this ought to be pretty straightforward. Pseudo-code, but you can solve this a few ways...

SELECT 
   * 
FROM 
   Table1 
   JOIN TABLE2 ON Table1.orderlist_email = TABLE2.email
   Table1.flag1 = 0 
   AND TABLE2.flag2 = 0 

Alternatively, you can add the WHERE conditions to the JOIN like so:

SELECT 
   * 
FROM 
   Table1 
   JOIN TABLE2 ON Table1.orderlist_email = TABLE2.email
   AND Table1.flag1 = 0 
   AND TABLE2.flag2 = 0 

I think your concern is whether or not this means the engine will still perform a full scan of both tables, rather than sticking with a "pre-filtered" set it will attempt to join. Modern engines should be clever enough to figure this stuff out, but based on the complexity of your query, your mileage might vary.

SchmitzIT
  • 9,227
  • 9
  • 65
  • 92