0

我想要ip不在 DHCP 范围内的记录。该ip表有上万条记录,范围约千。

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') 
);

(不幸的是,这在 sqlfiddle 上不起作用(不支持inet_aton?))

这不起作用:

SELECT ip FROM ip WHERE ip NOT BETWEEN(SELECT start,end FROM dhcprange)

想法?

4

2 回答 2

2

有几种方法可以做到这一点。最好的方法是像这样使用LEFT JOIN/ IS NULL

SELECT ip
FROM ip
LEFT JOIN dhcpranges ON ip BETWEEN start AND end
WHERE start IS NULL

你可以做一个不相关的子查询:

SELECT ip
FROM ip
WHERE ip NOT IN (SELECT ip FROM ip INNER JOIN dhcpranges WHERE ip BETWEEN start AND end)

或使用相关子查询:

SELECT a.ip
FROM ip a
WHERE NOT EXISTS (SELECT 1 FROM dhcpranges WHERE a.ip BETWEEN start AND end)
于 2012-07-05T06:54:57.603 回答
2
SELECT i.ip 
FROM ip i 
WHERE NOT EXISTS (
   SELECT NULL
   FROM dhcprange d
   WHERE i.ip BETWEEN d.start AND d.end)
于 2012-07-05T06:57:32.373 回答