对于产品表上的某些过滤子条件,我想找出这些过滤产品的不同类别(数百万种产品)。
明确的做法
use-> preferences.edit().remove("key").commit();
当涉及很多行时,需要很长时间才能完成(相反,使用SELECT DISTINCT category_id FROM "products" WHERE _conditions_
并没有太大变化)
根据https://wiki.postgresql.org/wiki/Loose_indexscan,当不同的col上只有相对少量的不同值时(就像这里有~30个类别的情况一样),条件
GROUP BY
可以重新表示为递归CTE
SELECT DISTINCT category_id FROM "products"
在我的用例中实际上表现更好(milisecons而不是秒)。 但它没有条件。
如何添加' WITH RECURSIVE t AS (
SELECT MIN(category_id) AS category_id FROM "products"
UNION ALL
SELECT (SELECT MIN(category_id) FROM "products" WHERE category_id > t.category_id)
FROM t WHERE t.category_id IS NOT NULL
)
SELECT category_id FROM t WHERE category_id IS NOT NULL
UNION ALL
SELECT NULL WHERE EXISTS(SELECT 1 FROM "products" WHERE category_id IS NULL);
'适当地适应递归CTE?
答案 0 :(得分:1)
WITH RECURSIVE t AS (
SELECT MIN(category_id) AS category_id FROM "products" WHERE _conditions_
UNION ALL
SELECT (SELECT MIN(category_id) FROM "products" WHERE category_id > t.category_id AND _conditions_ )
FROM t WHERE t.category_id IS NOT NULL
)
SELECT category_id FROM t WHERE category_id IS NOT NULL
UNION ALL
SELECT NULL WHERE EXISTS(SELECT 1 FROM "products" WHERE category_id IS NULL AND _conditions_);
喜欢这个。 条件中有三个。