我有一个Product
模型有很多Sku
个,每个产品也可以包含Customization
,其中包括要素。架构看起来像这样:
Product
| id | category_id | title | image |
Sku
| id | product_id | subtitle | price |
Customization
| id | product_id | title | featured |
我根据category_id及其Product
的价格对Sku
进行过滤/排序:
SELECT id, title, image, prices
FROM (
SELECT p.id, p.title, p.image, array_agg(s.price) as prices
FROM "Products" p
JOIN "Skus" s
ON p.id = s.product_id
WHERE p.category_id in (1,2,3,4) AND s.price > 99
GROUP BY p.id
) x
ORDER BY id DESC;
我想为Product
拥有Customization
的{{1}}添加额外的过滤器。
是否可以包含另一个featured = true
来执行此操作,还是有更好的方法?
答案 0 :(得分:2)
首先,您不需要子查询。其次,您可以使用JOIN
(或IN
或EXISTS
)执行此操作:
SELECT p.id, p.title, p.image, array_agg(s.price) as prices
FROM "Products" p JOIN
"Skus" s
ON p.id = s.product_id JOIN
Customization c
ON p.id = c.product_id AND c.featured = true
WHERE p.category_id in (1, 2, 3, 4) AND s.price > 99
GROUP BY p.id
ORDER BY p.id DESC