Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 从另一个表中选择范围之间的记录_Sql_Sql Server_Sql Server 2008 - Fatal编程技术网

Sql 从另一个表中选择范围之间的记录

Sql 从另一个表中选择范围之间的记录,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,我有两个表,比如Table1和Table2 表1 ╔════╦════╗ ║ ID ║ RN ║ ╠════╬════╣ ║ 11 ║ 1 ║ ║ 12 ║ 2 ║ ║ 13 ║ 3 ║ ║ 14 ║ 4 ║ ║ 15 ║ 5 ║ ║ 16 ║ 6 ║ ║ 17 ║ 7 ║ ║ 18 ║ 8 ║ ║ 19 ║ 9 ║ ║ 10 ║ 10 ║ ╚════╩════╝ 表2 ╔════╦════════╦══════╗ ║ ID ║ FromRN ║ ToRN ║ ╠════╬═

我有两个表,比如
Table1
Table2

表1

╔════╦════╗
║ ID ║ RN ║
╠════╬════╣
║ 11 ║ 1  ║
║ 12 ║ 2  ║
║ 13 ║ 3  ║
║ 14 ║ 4  ║
║ 15 ║ 5  ║
║ 16 ║ 6  ║
║ 17 ║ 7  ║
║ 18 ║ 8  ║
║ 19 ║ 9  ║
║ 10 ║ 10 ║
╚════╩════╝
表2

╔════╦════════╦══════╗
║ ID ║ FromRN ║ ToRN ║
╠════╬════════╬══════╣
║  1 ║    1   ║  3   ║
║  2 ║    6   ║  8   ║  
║  3 ║    10  ║  10  ║
╚════╩════════╩══════╝
我想要
表1
中的所有记录,其
RN
位于
表2
FromRN
撕破
之间的任何范围内

因此,我的预期输出是:

╔════╦════╗
║ ID ║ RN ║
╠════╬════╣
║ 11 ║ 1  ║
║ 12 ║ 2  ║
║ 13 ║ 3  ║
║ 16 ║ 6  ║
║ 17 ║ 7  ║
║ 18 ║ 8  ║
║ 10 ║ 10 ║
╚════╩════╝
可在以下位置找到用于创建架构的SQLFiddle:


您可以对两个表进行
内部联接
,从
表1
中筛选出
RN
值不在
表2中任何范围内的记录:

SELECT t1.ID, t1.RN
FROM Table1 t1
INNER JOIN Table2 t2
    ON t1.RN >= t2.FromRN AND t1.RN <= t2.ToRN
选择t1.ID,t1.RN
来自表1 t1
内连接表2 t2

在t1.RN>=t2.FromRN和t1.RN上,另一种解决方案是使用
存在
-

SELECT
*
FROM table1 t1
WHERE EXISTS (SELECT 1 FROM table2
    WHERE t1.rn >= FromRN
    AND t1.rn <= ToRN)
您可以尝试以下方法:

select t1.Id, t1.RN
from table1 t1
inner join table2 t2
on t1.Rn between t2.FromRn and t2.ToRn
select t1.Id, t1.RN
from table1 t1
inner join table2 t2
on t1.Rn between t2.FromRn and t2.ToRn