我正在使用SQLITE3 3.14.2并尝试执行以下操作:
给出两个表IP和lookem:
drop table IP;
create table IP(IP TEXT,
Name TEXT);
insert into IP values('10.5.6.7','Joe');
insert into IP values('10.6.6.7','Joe');
insert into IP values('10.2.3.4','Frank');
insert into IP values('10.3.5.7','David');
insert into IP values('10.34.56.78','David');
--select * from IP;
drop table lookem;
create table lookem(IP TEXT,
Name TEXT);
insert into lookem values('','Joe'); -- Exclude Joe for All IPs
insert into lookem values('','George'); -- Exclude George for all IPs
insert into lookem values('10.4.5.6','Frank');-- Excl Frank for 1 ip
insert into lookem values('10.34.56.78','David');-- Excl David on Specific IP
--select * from lookem;
select a.ip,a.name,b.name,b.ip from lookem a join ip b on
(b.name like case when a.name='' then '%' else a.name end) and
(b.ip like case when a.ip='' then '%' else a.ip end);
以上选择正确地适用于我,显示lookem表与多个标准上的IP表匹配的所有情况,用通配符替换空值。
|Joe|Joe|10.5.6.7
|Joe|Joe|10.6.6.7
10.34.56.78|David|David|10.34.56.78
然而,相反的是什么?我真正需要的是对比赛的排除。换句话说,将返回一个查询:
10.3.5.7|David
10.2.3.4|Frank
唯一的结果。提前感谢您的帮助。
答案 0 :(得分:1)
以下是使用NOT EXISTS
SELECT a.ip,
a.NAME
FROM IP a
WHERE NOT EXISTS (SELECT 1
FROM lookem b
WHERE ( a.IP = b.ip
OR b.ip = '' )
AND a.NAME = b.NAME)
如果您想要使用lookem
表格选择列,请使用Left JOIN
SELECT a.ip,
a.NAME
FROM IP a
LEFT JOIN lookem b
ON ( a.IP = b.ip
OR b.ip = '' )
AND a.NAME = b.NAME
WHERE b.NAME IS NULL
您的第一个查询也可以使用EXISTS
SELECT a.ip,
a.NAME
FROM IP a
WHERE EXISTS (SELECT 1
FROM lookem b
WHERE ( a.IP = b.ip
OR b.ip = '' )
AND a.NAME = b.NAME)
如果您想要使用lookem
表格选择列,请使用Inner JOIN
SELECT a.ip,
a.NAME
FROM IP a
JOIN lookem b
ON ( a.IP = b.ip
OR b.ip = '' )
AND a.NAME = b.NAME