【问题标题】:SQL : ids containing specific arrays in a specific waySQL:以特定方式包含特定数组的 id
【发布时间】:2018-08-15 14:21:02
【问题描述】:

一个项目table: items 有许多分类法table: taxonomies 使用连接表item_taxonomies (item_id, taxonomy_id)

使用分类组搜索项目。

例子:

taxo_group_1 = [1, 2, 3]
taxo_group_2 = [4, 5]

sql 应该以这种方式找到两个数组中包含taxonomies 的所有items

如果我有这些元素:

item_1 id=1
   taxo_1 id=11
   taxo_2 id=12
   taxo_3 id=13

item_2 id=2
   taxo_3 id=13
   taxo_4 id=14

使用[11, 12][13] 搜索将返回item_1 而不是item_2,因为item_1 具有分类法in [11, 12] AND in [13]

item_2 不会被返回,因为它在[11, 12] 中没有分类法

到目前为止:

"taxonomies"."id" IN (11, 12, 13) AND "taxonomies"."id" IN (13)

当然不行。

【问题讨论】:

  • -1 的人几乎都是有用的。至少留下评论。权力带来责任。

标签: mysql sql ruby-on-rails ruby postgresql


【解决方案1】:

您可以使用此查询获得所需的输出:

select item from (
    select item, count(distinct taxonomy_id) as count from items  
    join taxonomies on items.item_id = taxonomies.item_id
    where taxonomies.taxonomy_id in (11,12,13)
    group by item
) as T where count = 3

【讨论】:

    【解决方案2】:

    我的理解有点不同。他/她想找到所有恰好具有 11、12 和 13 作为分类 ID 的项目。

    select item from joinedTable 
    where taxonomy_id in (11,12,13)
    group by item
    having count(distinct taxonomy_id) = 3
    

    但实际上我对这个请求有点困惑。

    【讨论】:

      【解决方案3】:

      如果我很好理解您的问题,您希望获得一个在条目中获取所有 id 的组,在 sql 中它将是:

      SELECT [...] WHERE taxonomies.id = 11 
         AND taxonomies.id = 12 
         AND taxonomies.id = 13
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-01-13
        • 2022-01-27
        • 1970-01-01
        • 2017-03-19
        • 1970-01-01
        • 2021-07-02
        • 2013-03-31
        相关资源
        最近更新 更多