如何查找一组数字在两个数字之间的行?

时间:2010-07-13 18:38:07

标签: sql sql-server tsql

我有一个返回一组数字的查询:

SELECT Sequence FROM Table1 WHERE Hash=2783342

返回:

578
642
313

现在,我想在第一个表中找到所有行中的任何一行,其中任何一组数字都位于另外两列之间。为了说明的目的,我只选了578,但我也想要其他所有:

SELECT * FROM Table1 WHERE 578 BETWEEN Sequence AND SequenceEnd

1 个答案:

答案 0 :(得分:2)

使用JOIN,但存在重复的风险:

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

使用EXISTS,没有重复的风险:

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)