SQL IN BETWEEN. Comparing records and ranges (two different tables)
-
19-06-2021 - |
Question
I want records from ip
which are not in a DHCP range. The ip
table has over ten thousand records, the ranges about thousand.
CREATE TABLE ip (ip int);
CREATE TABLE dhcprange (start int,end int);
INSERT INTO found_ips VALUES
(INET_ATON('10.0.0.10')),
(INET_ATON('10.0.0.11')),
(INET_ATON('10.0.0.12')),
(INET_ATON('10.0.0.51')),
(INET_ATON('10.0.0.52')
);
INSERT INTO dhcpranges VALUES
(INET_ATON('10.0.0.50'),INET_ATON('10.0.0.60'),
(INET_ATON('10.0.0.70'),INET_ATON('10.0.0.100')
);
(This unfortunately does not work on sqlfiddle (inet_aton isn't supported?))
This doesn't work:
SELECT ip FROM ip WHERE ip NOT BETWEEN(SELECT start,end FROM dhcprange)
Ideas?
Solution
SELECT i.ip
FROM ip i
WHERE NOT EXISTS (
SELECT NULL
FROM dhcprange d
WHERE i.ip BETWEEN d.start AND d.end)
OTHER TIPS
A few ways you could do this. The best way would be to use a LEFT JOIN
/ IS NULL
like so:
SELECT ip
FROM ip
LEFT JOIN dhcpranges ON ip BETWEEN start AND end
WHERE start IS NULL
You could do a non-correlated subquery:
SELECT ip
FROM ip
WHERE ip NOT IN (SELECT ip FROM ip INNER JOIN dhcpranges WHERE ip BETWEEN start AND end)
Or use a correlated subquery:
SELECT a.ip
FROM ip a
WHERE NOT EXISTS (SELECT 1 FROM dhcpranges WHERE a.ip BETWEEN start AND end)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow