首页 > 解决方案 > SQL如何查找行中的缺失值

问题描述

我有一个数据库和一个外部文件。这两个共享的是产品的参考代码。

但是在外部文件中,我保存了所有参考代码,而数据库中仍然缺少很多。有没有办法进行查询,以便我可以检查给定表中我的数据库中缺少哪些值?

无需担心 XML 如何与数据库交互。我已经通过 PHP 和 simplexml 实现了这一点。在这种情况下,我主要是在努力使用查询。

数据库 XML 文件
AJS2S AJS2S
ABBB2 ABBB2
JJI90K
JJJJ92

标签: phpmysqlsqldatabasesubquery

解决方案


如果您手头有一个值列表,并且想要检查表中缺少哪些值,请在union all子查询中枚举它们,然后使用not exists

select x.product_code
from (
    select 'AJS2S' as product_code
    union all select 'ABBB2'
    union all ...
) x
where not exists (select 1 from mytable t where t.product_code = x.product_code)

或者,在最新版本的 MySQL(8.0.19 或更高版本)中,您可以使用values()行构造函数:

select x.product_code
from (values row('AJS2S'), row('ABBB2'), ...) x(product_code)
where not exists (select 1 from mytable t where t.product_code = x.product_code)

当然,如果您已经将 xml 数据加载到表中,例如xmltable,那么您可以使用它来代替子查询:

select x.product_code
from xmltable x(product_code)
where not exists (select 1 from mytable t where t.product_code = x.product_code)

推荐阅读