【问题标题】:PostgreSQL - Help comparing two tables against three specific columnsPostgreSQL - 帮助比较两个表与三个特定列
【发布时间】:2019-10-01 00:13:26
【问题描述】:

我需要匹配两个表中的三列。查询应在 t1 中选择一行,然后在 t2 中搜索下面列出的所有三列都匹配的任何行。

tbl_staged_documentation (t1 for reference)
orgname|name|subnet|customerid|customername|ipaddress|prefix

tbl_active_networks (t2 for reference)
orgid|ipaddress|prefixlength|sitename|siteid|name

这是三列

t1.customerid = t2.orgid
t1.ipaddress = t2.ipaddress
t1.prefix = t2.prefixlength

我研究了 JOIN 和 UNION。 UNION 看起来可以撕掉重复项,但我无法得到它。也不加入。

似乎这两个选项之一是要走的路,但我不清楚该怎么做。

select *
from tbl_staged_documentation t1
join tbl_active_networks t2
  on t1.customerid = t2.orgid
  and t1.ipaddress = t2.ipaddress
  and t1.prefix = t2.prefixlength
where
  t1.customerid = t2.orgid AND t1.ipaddress != t2.ipaddress AND t1.prefix != t2.prefixLength;

还尝试了以下UNION

select customerid, ipaddress, prefix from tbl_staged_documentation
union
select orgid, ipaddress, prefixlength from tbl_active_networks;

最终,我试图找出来自 t1 的哪些网络信息在 t2 中不存在。 t1 是事实的来源。 t2 包含生产系统中的数据。

来自 t1 的数据将动态更新到 t2,但由于 t2 的数据来自的系统有严格的速率限制,我试图在运行 API 调用之前对其进行清理。

【问题讨论】:

    标签: sql database postgresql


    【解决方案1】:

    我正在尝试找出来自 t1 的哪些网络信息在 t2 中不存在

    这正是 NOT EXISTS 运算符的用途:

    select *
    from tbl_staged_documentation t1
    where not exists (select *
                      from tbl_active_networks t2
                      where t1.customerid = t2.orgid
                        and t1.ipaddress = t2.ipaddress
                        and t1.prefix = t2.prefixlength)
    

    【讨论】:

      【解决方案2】:

      不是 100% 确定您的问题,但我认为您可能需要的是“反连接”,如:

      select t1.*
      from tbl_staged_documentation t1
      left join tbl_active_networks t2
        on t1.customerid = t2.orgid
        and t1.ipaddress = t2.ipaddress
        and t1.prefix = t2.prefixlength
      where t2.orgid is null
      

      即:

      • 使用匹配条件:

        t1.customerid = t2.orgid
        t1.ipaddress = t2.ipaddress
        t1.prefix = t2.prefixlength
        
      • 查找t1中的哪些行在t2中没有任何匹配行。

      【讨论】:

        【解决方案3】:

        @a_horse_with_no_name 应该是对的。

        这里有更多关于subquery expressions 的信息,包括 (NOT) EXISTS 和 (NOT) IN。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-08-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多