【问题标题】:Verify two columns of two different tables match exactly验证两个不同表的两列完全匹配
【发布时间】:2011-02-05 20:42:35
【问题描述】:

在更深层次的视图中编写视图和嵌套视图时,我有时会遗漏某些内容并最终丢失行/数据。如何检查两个不同表中的列是否具有完全匹配的数据?

例子:

select count(distinct table1.col1)
  from table1
 where table1.col1 not in (select distinct table2.col1 
                             from table2);

这将返回 table1.col1 中不在 table2 中的值的数量。但是,我不知道这是一个好的解决方案,因为它不计算 table1.col1 中不存在的 table2.col1 值。

【问题讨论】:

  • 当然嵌套视图通常是一件坏事(至少在 SQL Server 中)。在开发中看起来不错,但是一旦你进入 prod 并且有很多记录,你可以通过嵌套视图来关闭系统。我会通过向基表添加几百万条测试记录来测试这些嵌套视图。
  • 确实,我最终会重写查询,创建一串嵌套视图是为了在开始时进行概念验证,以验证数据是否按照我想要的方式形成。当数据库推出时,我会重构视图。

标签: sql database sqlite select


【解决方案1】:
declare @count int, @count2 int


select @count = count(distinct table1.col1)
  from table1
 where table1.col1 not in (select distinct table2.col1 
                             from table2)

select @count2 = count(distinct table2.col1)
  from table2
 where table2.col1 not in (select distinct table1.col1 
                             from table1)

select @count + @count2

【讨论】:

  • 使用 SQLite,我可以使用 MS SQL 或 MySQL 等内部变量吗?
  • 我不认为它被重新标记,但它被标记为 SQL :)
【解决方案2】:

用途:

SELECT MAX(x.t1_missing_count) AS t1_missing_count, 
       MAX(x.t2_missing_count) AS t2_missing_count
  FROM (
SELECT COUNT(DISTINCT t1.col1) AS t1_missing_count,
       NULL AS t2_missing_count
  FROM TABLE_1 t1
 WHERE t1.col1 NOT IN (SELECT DISTINCT t2.col1 
                         FROM TABLE_2 t2)
UNION ALL
SELECT NULL,
       COUNT(DISTINCT t2.col1),           
  FROM TABLE_2 t2
 WHERE t2.col1 NOT IN (SELECT DISTINCT t1.col1 
                         FROM TABLE_1 t1)) x

【讨论】:

  • 不知道为什么我不考虑使用 UNION。所以我使用 NOT IN 子句查询对于这样的操作是否可行?
  • @galford13x:我不知道这三个中的哪一个 - NOT EXISTS、NOT IN 和 LEFT JOIN/IS NULL - 目前使用效率最高。
【解决方案3】:
select count(*) from (

select
table1.col1 from table1 left join table2 on table1.col1 = table2.col2
where table2.col1 is null

union

select table2.col1 from table2 left join table 1 on table2.col1 = table1.col1
where table1.col1 is null

)

【讨论】:

    【解决方案4】:

    您可以使用两个EXCEPT 查询(或合并它们)来检查:

    SELECT DISTINCT col1
    FROM table1
    EXCEPT
    SELECT DISTINCT col1
    FROM table2
    

    这将显示 table1 中存在的值,但 table2 中不存在。然后再次运行,表名相反。

    【讨论】:

    • 我喜欢简洁。我用 SELECT count() 包装它以获得差异的数量。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 2018-01-07
    • 2020-04-28
    • 1970-01-01
    相关资源
    最近更新 更多