Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a view from a union query

Tags:

sql

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

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.

like image 631
jakebird451 Avatar asked Mar 29 '12 01:03

jakebird451


2 Answers

There's a decent chance this will work — if your DBMS allows union queries in views.

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.

like image 141
Jonathan Leffler Avatar answered Sep 30 '22 17:09

Jonathan Leffler


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
like image 40
Steven Mastandrea Avatar answered Sep 30 '22 17:09

Steven Mastandrea