我很抱歉也要提出这个问题。但似乎我今天没有运气。我已将我的所有结果连接成“Unioned”,现在我试图将其推向视图。这应该也很简单,但我似乎无法改变各种组件以使其工作。这是我尝试使用的代码:
CREATE VIEW v AS
SELECT *
FROM
(
(SELECT maker, model, price FROM product NATURAL JOIN laptop)
UNION
(SELECT maker, model, price FROM product NATURAL JOIN pc)
UNION
(SELECT maker, model, price FROM product NATURAL JOIN printer)
) `Unioned`
错误:#1349 - View's SELECT contains a subquery in the FROM clause
我一直在尝试将各种组件封装到括号中。或者仅为创建视图创建一个新语句。这个问题应该很容易回答,但我只是没有看到它。
答案 0 :(得分:7)
如果您的DBMS允许在视图中进行联合查询,那么这将有可能发挥作用。
CREATE VIEW v AS
SELECT maker, model, price FROM product NATURAL JOIN laptop
UNION
SELECT maker, model, price FROM product NATURAL JOIN pc
UNION
SELECT maker, model, price FROM product NATURAL JOIN printer
你可能想要考虑UNION ALL而不是UNION(又名UNION DISTINCT),因为UNION DISTINCT几乎肯定会慢得多,特别是如果表很大的话。另一方面,您可能更喜欢不重复,在这种情况下UNION是正确的。
答案 1 :(得分:1)
尝试删除子查询,我认为这应该有效:
CREATE VIEW v AS
SELECT maker, model, price FROM product NATURAL JOIN laptop
UNION SELECT maker, model, price FROM product NATURAL JOIN pc
UNION SELECT maker, model, price FROM product NATURAL JOIN printer