简体   繁体   中英

SQL - how to select rows based upon values from a different table?

I've a table called ranges which looks like this-

create table ranges(low bigint, high bigint, id int);
insert into ranges values (10,20,100);
insert into ranges values (21,30,101);

I've another table which looks like this-

create table ip(ip bigint);
insert into ip values (12);

I want a query which will output the id from the ranges table if the ip from ip table is between low and high of ranges table.

For example, for the ip 12 , I want the output to be -

12,100

since 12 is between the low 10 and high 20 from the ranges table. What is the most efficient way of doing this? the column ip doesn't exist in the ranges table so I can't do a straightforward join.

You can join a table using range.

SELECT
    ip.ip, ranges.id
FROM
    ip
JOIN ranges ON ip.ip BETWEEN ranges.low AND ranges.high

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM