【问题标题】:SQL equivalent "$all" MongoDB operator on Repeated string重复字符串上的 SQL 等效“$all”MongoDB 运算符
【发布时间】:2020-12-29 16:41:15
【问题描述】:

假设如下数据结构:

  • MongoDB:{id:ObjectId,颜色:String[]}
  • SQL:列 ID(整数)、列颜色(重复字符串)

假设以下 MongoDB 查询:

collection.find({colors: {$all: ["blue", "orange", "yellow"]} })

SQL 中“$all”的等效运算符/符号是什么?请注意,与 $in 不同,$all 查找具有匹配所有值的该字段的文档(行),而不仅仅是其中的“一些”。

【问题讨论】:

    标签: sql database mongodb google-bigquery


    【解决方案1】:

    假设重复值没有重复,可以使用:

    select s.*
    from sql s
    where (select count(*)
           from unnest(s.colors) color
           where color in ('blue', 'orange', 'yellow')
          ) = 3;
    

    “3”是列表的大小。如果有重复,请改用count(distinct color)

    如果不想“记住”3,可以使用:

    with color_list as (
          select color
          from unnest(array['blue', 'orange', 'yellow']) color
         )
    select s.*
    from sql s
    where (select count(*)
           from unnest(s.colors) color join
                color_list cl
                using (color)
          ) = (select count(*) from color_list);
    

    甚至:

    select s.*
    from sql s
    where not exists (select 1
                      from unnest(array['blue', 'orange', 'yellow']) my_color left join
                           unnest(s.colors) color
                           on my_color = color
                      where color is null
                     );
    

    【讨论】:

      【解决方案2】:

      以下是 BigQuery 标准 SQL

      #standardSQL
      create temp function check_all(arr ANY TYPE, match ANY TYPE) as (
        array_length(array(
          select distinct m from unnest(match) m 
          join unnest(arr) m using(m)
        )) = array_length(array(
          select distinct m from unnest(match) m 
        ))
      );
      select *
      from `project.dataset.table`
      where  check_all(colors, ['blue', 'orange', 'yellow'])    
      

      如果适用于以下虚拟样本数据

      with `project.dataset.table` as (
        select 1 id, ['blue', 'orange', 'yellow', 'black'] colors union all
        select 2, ['blue', 'pink', 'yellow', 'green'] union all
        select 3, ['red', 'orange', 'blue', 'pink', 'yellow', 'green'] 
      )
      

      输出是

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多