Couchbase/N1QL: SELECT 来自参数提供的值列表

Couchbase/N1QL: SELECT FROM list of values provided by parameter

作为 的后续行动,我仍然希望获得每个 categoryId 的前 5 名产品,但我想提供一个预选的与我相关的 categoryId 列表。

从最初的问题 开始,我可以这样做:

SELECT u.*
FROM (SELECT DISTINCT RAW p.categoryId
      FROM products AS p
      WHERE p.categoryId IN $categoryIds) AS c
UNNEST (SELECT p1.*
    FROM products AS p1
    WHERE p1.categoryId = c
    ORDER BY p1.categoryId, p1.price DESC
    LIMIT 5) AS u;

其中命名参数 $categoryIds 将作为数组 ['cat1', 'cat2'] 提供。

SELECT DISTINCT RAW p.categoryId FROM products AS p WHERE p.categoryId IN $categoryIds 感觉有点低效,只是为了取回一些基本上又是我提供的类别 ID 列表的东西。

我相信有更有效的方式来表达这一点。类似于:

SELECT u.*
FROM (VALUES IN $categoryIds) AS c
UNNEST ...;
CREATE INDEX ix1 ON products(categoryId, price DESC);

因此 Unnest 中的以下子查询使用索引顺序并仅检索每个类别的前 5 个条目,而不管特定类别中的条目数

如果 $categoryIds 包含唯一条目

SELECT u.*
FROM $categoryIds AS c
UNNEST (SELECT p1.*
       FROM products AS p1
       WHERE p1.categoryId = c
       ORDER BY p1.categoryId, p1.price DESC
       LIMIT 5) AS u;

对于 non-unique 个条目

SELECT u.*
FROM (SELECT DISTINCT RAW c1
      FROM $categoryIds AS c1 ) AS c
UNNEST (SELECT p1.*
    FROM products AS p1
    WHERE p1.categoryId = c
    ORDER BY p1.categoryId, p1.price DESC
    LIMIT 5) AS u;