【问题标题】:selecting only records which are not present in the second table仅选择第二个表中不存在的记录
【发布时间】:2017-12-18 20:42:01
【问题描述】:

我有一个带有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

【问题讨论】:

  • 有什么问题?
  • 您只是想知道如何使用 JOIN 来完成这项工作吗?
  • 问题是table1中hostname的值可以是sa77.comsa77我想检查这两个值
  • FQDN for severs 是什么意思??
  • 在给定的示例中,table1 看起来总是有 .com,而 table2 可能有也可能没有。请澄清。

标签: mysql sql join left-join inner-join


【解决方案1】:

我通常使用left joinwhere is null 来执行此操作,如下所示:

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

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

【讨论】:

  • explainextended.com/2009/09/18/…开始,这确实应该是最有效的方式
  • 同意——它产生了正确的结果,并且比其他示例中建议的使用 CONCAT 更有效。
【解决方案2】:

怎么样:

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

但是您需要多解释一下您需要匹配哪些案例。

【讨论】:

  • 我已经编辑了我的问题。两个表中的名称或主机名中的服务器名称可能是完全限定的,也可能不是完全限定的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-03
  • 1970-01-01
相关资源
最近更新 更多