Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Records between Range from another table

I have two tables, say Table1 and Table2

Table1

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

Table2

╔════╦════════╦══════╗
║ ID ║ FromRN ║ ToRN ║
╠════╬════════╬══════╣
║  1 ║    1   ║  3   ║
║  2 ║    6   ║  8   ║  
║  3 ║    10  ║  10  ║
╚════╩════════╩══════╝

I want all those records from Table1 whose RN lies between any range between FromRN and ToRN in Table2

So my expected output is:

╔════╦════╗
║ ID ║ RN ║
╠════╬════╣
║ 11 ║ 1  ║
║ 12 ║ 2  ║
║ 13 ║ 3  ║
║ 16 ║ 6  ║
║ 17 ║ 7  ║
║ 18 ║ 8  ║
║ 10 ║ 10 ║
╚════╩════╝

SQLFiddle to create schema can be found here:

http://sqlfiddle.com/#!3/90d50

like image 611
Pradeep Kumar Avatar asked Feb 02 '16 08:02

Pradeep Kumar


1 Answers

You can do an INNER JOIN of the two tables to filter out those records from Table1 whose RN values do not fall into any range in Table2:

SELECT t1.ID, t1.RN
FROM Table1 t1
INNER JOIN Table2 t2
    ON t1.RN >= t2.FromRN AND t1.RN <= t2.ToRN

Follow the link below for a running demo (courtesy of the OP):

SQLFiddle

like image 177
Tim Biegeleisen Avatar answered Nov 11 '22 13:11

Tim Biegeleisen