我一直在研究这个问题,这让我疯狂。
我有一个产品表和一个包含子产品的表。 简而言之,我想创建一个包含产品数据的视图,以及子产品的最低(折扣)价格。 (想想一件衬衫,有几个子产品(颜色/尺码)等)
其次我想在VIEW中使用这个查询,这部分让我疯狂。
我现在的查询:
SELECT m.* from product_items m join
(select product_id, min(price_discount) md
from product_items group by product_id) mm
on m.product_id=mm.product_id and m.price_discount=md
这个查询正常,我收到了很好的结果。但现在我想创建一个视图(vw_product_lowest)。
然后是错误:ERROR 1349 (HY000): View's SELECT contains a subquery in the FROM clause
有人可以帮我将该查询转换为兼容的VIEW查询吗?谢谢!
答案 0 :(得分:9)
您有几个选择:
将子查询放入视图中(可能很慢,因为生成的视图没有用于执行后续连接的索引):
CREATE VIEW mm AS
SELECT product_id, MIN(price_discount) price_discount
FROM product_items
GROUP BY product_id
;
CREATE VIEW my_view AS
SELECT * FROM product_items m NATURAL JOIN mm
;
使用correlated subquery(也可能很慢,因为必须针对表中的每条记录评估子查询 - 使用(product_id, price_discount)
上的复合索引可以获得最佳性能): / p>
CREATE VIEW my_view AS
SELECT * FROM product_items m WHERE price_discount = (
SELECT MIN(mm.price_discount)
FROM product_items mm
WHERE mm.product_id = m.product_id
)
;
优化相关子查询using the EXISTS
strategy(也将受益于(product_id, price_discount)
上的复合索引):
CREATE VIEW my_view AS
SELECT * FROM product_items m WHERE NOT EXISTS (
SELECT 1
FROM product_items mm
WHERE mm.product_id = m.product_id
AND mm.price_discount < m.price_discount
LIMIT 1
)
;
答案 1 :(得分:6)
根据手册,VIEW
不能包含子查询。如果您确实想在查询中创建VIEW
,则需要为子查询创建单独的视图,例如
第一次观看
CREATE VIEW MinimumPrice
AS
SELECT product_id, MIN(price_discount) md
FROM product_items
GROUP BY product_id
第二次观看
CREATE VIEW MinimumPriceList
AS
SELECT m.*
FROM product_items m
INNER JOIN MinimumPrice mm
ON m.product_id = mm.product_id AND
m.price_discount = mm.md
查询MAIN VIEW,
SELECT * FROM MinimumPriceList
A view definition is subject to the following restrictions: FROM MySQL MANUAL