tags:

views:

73

answers:

2

I need a help with selecting the rows in a table depending on the status in previous table.

Any help will be highly appreciated.

A: 
select a.column1, a.column2, a.status
from Table1 a inner join Table2 b
on (a.column1 = b.column1 or a.column2 = b.column1)
where a.status = 1 
Raj
This returns duplicates.
Mark Byers
Throwing in a `DISTINCT` to eleminate duplicates will not work?
DrColossos
@DrColossos: Even then I still think it gives the wrong result in some cases. b.column2 is not even mentioned in the query.
Mark Byers
A: 

Here's a solution using only a JOIN, but I'm assuming that you have a primary key on each table, called ID.

SELECT * FROM Table2 t2
INNER JOIN Table1 t1
ON t2.Status = 1 AND
  (t1.Column1 = t2.Column1 OR t1.Column1 = t2.Column2 OR
   t1.Column2 = t2.Column1 OR t1.Column2 = t2.Column2)
GROUP BY t2.ID

An INNER JOIN requires all conditions to be true in order for the row to be returned. The GROUP BY clause effectively removes the duplicate rows from Table2 that match multiple rows in Table1.

Marcus Adams