【问题标题】:SQL How to find missing values in rowsSQL如何查找行中的缺失值
【发布时间】:2020-12-08 17:20:30
【问题描述】:

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

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

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

Database XML File
AJS2S AJS2S
ABBB2 ABBB2
JJI90K
JJJJ92

【问题讨论】:

    标签: php mysql sql database subquery


    【解决方案1】:

    如果您手头有一个值列表并且想要检查表中缺少哪些值,您可以在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)
    

    【讨论】:

    • 我有一个 foreach 循环 foreach($xml->Products->Product as $pro) 然后创建一个数组 $results[$counter] = array( 'Code' => isset( $pro->Code) ? (string)$pro->Code : false, 所述数组由 .xml 文件中的几个属性索引,如下所示: $ref = $results[$counter]['Code'];第三种解决方案是否可以适应这个问题?
    • 当我运行 php 文件而不是给我数据库中缺少的参考代码时,它返回给我无尽的 'falsefalsefalsefalsefalsefalse'
    【解决方案2】:

    你会使用not exists:

    select code
    from xml
    where not exists (select 1 from database d where d.code = xml.code);
    

    这会检索每个代码——因此它可能有很多重复项。您可以使用group by进行总结:

    select code, count(*)
    from xml
    where not exists (select 1 from database d where d.code = xml.code)
    group by code;
    

    【讨论】:

    • 当我运行 php 文件而不是给我数据库中缺少的参考代码时,它返回给我无尽的 'falsefalsefalsefalsefalsefalse'
    • @Haykne 。 . .除非那是 XML 文件中的代码,否则这样的结果似乎表明查询 XML 文件有问题
    猜你喜欢
    • 1970-01-01
    • 2019-12-01
    • 1970-01-01
    • 2012-07-12
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多