【问题标题】:How to apply lists of filter values on two columns in lock-step?如何在锁定步骤中在两列上应用过滤器值列表?
【发布时间】:2020-09-04 23:00:22
【问题描述】:

假设我的表格包含以下列和记录:

id shop_id product_id
1  1       1
2  1       2
3  2       1
4  2       3

当查询如下所示时,我想运行单个查询以获取 ID 1 和 ID 4 记录:

ShopProduct.where(shop_id: 1, product_id: 1).where(shop_id: 2, product_id: 3)

问题是当我尝试像这样简化时:

ShopProduct.where(shop_id: [1,2], product_id: [1,3])

然后我得到 三个 记录,而不是预期的两个。

【问题讨论】:

    标签: sql ruby-on-rails postgresql


    【解决方案1】:

    少量输入对的简单解决方案:ROW values:

    SELECT *
    FROM   "ShopProduct"
    WHERE  (shop_id, product_id) IN ((1,1), (2,3));
    

    相关:

    如果您有两个长数组要以“锁步”方式处理,其他形式可能会更快/更方便。喜欢:并行(以锁步方式)取消嵌套两个数组,然后加入:

    SELECT *
    FROM   unnest('{1,2}'::int[], '{1,3}'::int[]) t(shop_id, product_id)
    JOIN   "ShopProduct" USING (shop_id, product_id);
    

    函数unnest() 有一个重载版本,它接受多个输入数组。见:

    db小提琴here

    【讨论】:

      【解决方案2】:

      你可以用or condition从rails 5开始实现它

      ShopProduct.where(shop_id: 1, product_id: 1).or(ShopProduct.where(shop_id: 2, product_id: 3))
      

      相关:

      Rails find records using an array of hashes

      【讨论】:

        猜你喜欢
        • 2017-02-11
        • 1970-01-01
        • 2021-01-23
        • 1970-01-01
        • 2022-11-23
        • 1970-01-01
        • 2020-03-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多