仅选择第二个表中不存在的记录

问题描述 投票:0回答:2

我有一个带hostname字段的mysql table1和以下值:

HostName
-----
sa77.com
ca77cded.com
sa65yacd.com
ca65zededs.com
sa88y.com
sa99ujk8.com

我有另一个table2,它有name字段(携带主机名值)。

Name
-----
sa77
ca77cded.com
sa65yacd
ca65zededs.com

我想从table2中选择table1中不存在的记录

select * 
from table2 
where name NOT IN (select hostname from table1);

namehostname中2个表中任意一个的服务器名称可能是也可能不是完全限定的。例如,sa77可以具有sa77.abc.comsa77.cdesa77的值。服务器可以有多个域值

sa77.abc.com匹配sa77sa77.abc我基本上需要比较值sa77

mysql sql join left-join inner-join
2个回答
1
投票

我通常使用left joinwhere is null这样做,像这样:

select * 
from table2
left join table1 on table2.name=table1.hostname
where table1.hostname is null;

(编辑,因为你希望table2中的记录不在table1中,而不是相反。)


0
投票

关于什么:

where name NOT IN (select hostname from table1)
  and CONCAT(name, '.com') NOT IN (select hostname from table1);

但是你需要解释一下你需要匹配的案例。

© www.soinside.com 2019 - 2024. All rights reserved.