SQL 从联合查询创建视图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9918117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating a view from a union query
提问by jakebird451
I'm sorry to have to bring up this as well. But it doesn't seem like I am getting any luck today. I have concatenated all my results into "Unioned" and am now attempting to push this into a view. This should be simple as well, but I can't seem to shift various components around to get it to work. This is the code I am trying to use:
我也很抱歉不得不提出这个问题。但我今天似乎没有走运。我已将所有结果连接到“联合”中,现在正试图将其推入视图中。这也应该很简单,但我似乎无法移动各种组件来使其工作。这是我尝试使用的代码:
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`
Error: #1349 - View's SELECT contains a subquery in the FROM clause
错误: #1349 - View's SELECT contains a subquery in the FROM clause
I have been trying to encapsulate various components into parenthesis. Or create a new statement just for creating the view. This question should be fairly simple to answer, but I'm just not seeing it.
我一直在尝试将各种组件封装到括号中。或者创建一个仅用于创建视图的新语句。这个问题应该很容易回答,但我只是没有看到。
回答by Jonathan Leffler
There's a decent chance this will work — if your DBMS allows union queries in views.
这很有可能会奏效——如果您的 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
You might want to consider UNION ALL instead of UNION (aka UNION DISTINCT) because UNION DISTINCT will almost certainly be considerably slower, especially if the tables are big. On the other hand, you may prefer to do without duplicates, in which case UNION is correct.
您可能需要考虑 UNION ALL 而不是 UNION(又名 UNION DISTINCT),因为 UNION DISTINCT 几乎肯定会慢得多,尤其是在表很大的情况下。另一方面,您可能更喜欢不使用重复项,在这种情况下 UNION 是正确的。
回答by Steven Mastandrea
Try removing the sub-queries, I think this should work:
尝试删除子查询,我认为这应该有效:
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