[英]How to filter nonaggregated query results by an aggregated column?
I'm creating a price comparison service.我正在创建一个价格比较服务。 Products from one
Site
are compared to products from one or more Sites
.来自一个
Site
的产品与来自一个或多个Sites
产品进行比较。 Products are matched from one Site
to another using a ProductMatch
table:使用
ProductMatch
表将产品从一个Site
匹配到另一个Site
:
Given the following query to extract products, together with their matches:给定以下查询以提取产品及其匹配项:
SELECT
p1.id AS p1_id, p1.name AS p1_name, p1.price AS p1_price,
p2.id AS p2_id, p2.name AS p2_name, p2.price AS p2_price,
m.time
FROM Product p1
LEFT JOIN ProductMatch m ON m.fromProduct_id = p1.id
LEFT JOIN Product p2 ON m.toProduct_id = p2.id
WHERE p1.site_id = 1;
How can I filter products whose price ( p1.price
) is lower than the minimum competitor price ( MIN(p2.price)
)?如何过滤价格 (
p1.price
) 低于最低竞争对手价格 ( MIN(p2.price)
) 的产品?
Using subqueries, here's how I would do it:使用子查询,这是我的做法:
SELECT
p1.id AS p1_id, p1.name AS p1_name, p1.price AS p1_price,
p2.id AS p2_id, p2.name AS p2_name, p2.price AS p2_price,
m.time
FROM Product p1
LEFT JOIN ProductMatch m ON m.fromProduct_id = p1.id
LEFT JOIN Product p2 ON m.toProduct_id = p2.id
WHERE p1.id IN (
SELECT x.id FROM (
SELECT _p1.id, _p1.price
FROM Product _p1
JOIN ProductMatch _m ON _m.fromProduct_id = _p1.id
JOIN Product _p2 ON _m.toProduct_id = _p2.id
WHERE _p1.site_id = 1
GROUP BY _p1.id
HAVING _p1.price < MIN(_p2.price)
) x
);
Is it possible to simplify this query to not use subqueries?是否可以简化此查询以不使用子查询?
My concerns:我的顾虑:
With MIN()
window function inside a CTE
which will be filtered:在将被过滤的
CTE
内使用MIN()
窗口函数:
WITH cte AS (
SELECT
p1.id AS p1_id, p1.name AS p1_name, p1.price AS p1_price,
p2.id AS p2_id, p2.name AS p2_name, p2.price AS p2_price,
m.time,
MIN(p2.price) OVER (PARTITION BY p1.id) AS min_price
FROM Product p1
LEFT JOIN ProductMatch m ON m.fromProduct_id = p1.id
LEFT JOIN Product p2 ON m.toProduct_id = p2.id
WHERE p1.site_id = 1
)
SELECT
p1_id, p1_name, p1_price,
p2_id, p2_name, p2_price,
time
FROM cte
WHERE p1_price < min_price
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.