tags:

views:

559

answers:

3

I need to write a select query that joins the tables based on a condition (in this case, based on a value in one of the columns). I would like to do something like this:

SELECT *
  FROM TableA
       INNER JOIN TableB ON (TableA.Column1 = TableB.Column1 OR TableA.Column1 = 0) -- Does not work!
+4  A: 

I'm not exactly sure what you are doing but it seems like you are looking for an outer join:

SELECT *
FROM TableA LEFT OUTER JOIN TableB ON TableA.Column1 = TableB.Column1
WHERE TableB.Column1 IS NOT NULL
   OR TableA.Column1 = 0
bobwienholt
Same exact answer I just wrote, only faster. :)
recursive
A: 

This should achieve what you need:

SELECT *
FROM TableA A
WHERE A.Column1 = 0
   OR EXISTS(
            SELECT B.Column1
            FROM TableB B
            WHERE B.Column1 = A.Column1
            );
JosephStyons
This doesn't select any columns from TableB.
recursive
A: 

If you want rows from Table A and rows from Table B, just use two select statements separated by a UNION command.

BoltBait