views:

42

answers:

1

I have a query which returns a set of numbers:

SELECT Sequence FROM Table1 WHERE Hash=2783342

Returns:

578
642
313

Now, I want to find all rows in the first table where any of that set of numbers is between two other columns. For the purpose of illustration, I am just picking 578, but I also want all of the rest:

SELECT * FROM Table1 WHERE 578 BETWEEN Sequence AND SequenceEnd
+2  A: 

Using a JOIN, but risks duplicates:

SELECT t.*
  FROM TABLE1 t
  JOIN (SELECT Sequence FROM Table1 WHERE Hash=2783342) x ON x.sequence BETWEEN t.sequence 
                                                                            AND t.sequenceend

Using EXISTS, no duplicate risk:

SELECT t.*
  FROM TABLE1 t
 WHERE EXISTS(SELECT NULL
                FROM TABLE1 x
               WHERE x.hash = 2783342
                 AND x.sequence BETWEEN t.sequence 
                                    AND t.sequenceend)
OMG Ponies
Since the table contains an IDENTITY column, in the JOIN example, could I simply use SELECT DISTINCT t.Id, t.* FROM TABLE1 ... It seems to return the same result set for me?
esac
With the DISTINCT, they both have the exact same execution plan in the end, so I guess it doesn't matter.
esac