【问题标题】:Iterate through results of SQLite query as input to subsequent query遍历 SQLite 查询的结果作为后续查询的输入
【发布时间】:2021-04-05 09:12:28
【问题描述】:

我有一个 SQLite 表,其中包含以下字段,这些字段表示从存储在磁盘上的单个文件中提取的元数据。每个文件都有一个记录:

__path      denotes the full path and filename (in effect the PK)
__dirpath   denotes the directory path excluding the filename
__dirname   denotes the directory name in which the file is found
refid       denotes an attribute of interest, pulled from the underlying file on disk
  1. 文件在创建时按 __dirname 分组和存储
  2. 中的所有文件 __dirname 应该具有相同的 refid,但 refid 有时不存在
  3. 作为起点,我想确定每个 __dirpath 有不合格的文件。

我对识别违规文件夹的查询如下:

SELECT __dirpath
  FROM (
           SELECT DISTINCT __dirpath,
                           __dirname,
                           refid
             FROM source
       )
 GROUP BY __dirpath
HAVING count( * ) > 1
 ORDER BY __dirpath, __dirname;

是否可以遍历查询的结果并将每个结果用作另一个查询的输入,而无需使用 Python 和 SQLite 之类的东西?例如,查看属于失败集的记录:

SELECT __dirpath, refid
  FROM source
 WHERE __dirpath = <nth result from aforementioned query>;

【问题讨论】:

    标签: sql sqlite loops count subquery


    【解决方案1】:

    如果您想要所有违规行,一个选项是:

    select t.*
    from (
        select t.*,
            min(refid) over(partition by __dirpath, __dirname) as min_refid,
            max(refid) over(partition by __dirpath, __dirname) as max_refid
        from mytable t
    ) t
    where min_refid <> max_refid
    

    逻辑是比较具有相同目录路径和目录名称的每组行的最小和最大refid。如果它们不同,则该行有问题。

    我们也可以使用exists - 这将更好地处理refid 中可能的null 值:

    select t.*
    from mytable t
    where exists (
        select 1
        from mytable t1
        where 
            t1.__dirpath = t.__dirpath 
            and t1.__dirname = t.__dirname
            and t1.ref_id is not t.ref_id
    )
    

    【讨论】:

    • 谢谢@GMB。我都尝试了,第一个执行相对较快,但忽略了 refid 为空的记录。第二次运行,但它对大约 60 万条记录的运行速度非常慢 - 在 __dirpath、__dirname 上建立索引,refid 解决了这个问题。真实表有更多字段,因此我将 t.* 替换为我所追求的特定字段。由于空值或备用值可能会导致 refid 不一致,因此第二个查询生成了正确的结果,列出了所有受影响的记录。
    猜你喜欢
    • 2015-12-16
    • 1970-01-01
    • 2016-07-08
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 2015-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多