Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data from two tables into one view

Tags:

Is it possible to grab data from two tables (that have the same fields) into one view. Basically, so the view sees the data as if it was one table.

like image 893
Marcin Avatar asked Jul 16 '10 17:07

Marcin


People also ask

How do you create a view between two tables?

You can create a view that combines data from two or more tables by naming more than one table in the FROM clause. In the following example procedure, the INVENTORY_LIST table contains a column of item numbers called ITEM_NUMBER and a column of item cost called UNIT_COST.

How can I merge two table data?

You can merge (combine) rows from one table into another simply by pasting the data in the first empty cells below the target table. The table will increase in size to include the new rows.

How do I combine data from multiple tables into one table in SQL?

Merging tables by columns. Multiple tables can be merged by columns in SQL using joins. Joins merge two tables based on the specified columns (generally, the primary key of one table and a foreign key of the other).


1 Answers

Yes, using a UNION -

CREATE VIEW vw_combined AS    SELECT * FROM TABLE1    UNION ALL    SELECT * FROM TABLE2 

...requires that there be the same number of columns, and the data types match at each position.

..preferrably, using a JOIN:

CREATE VIEW vw_combined AS    SELECT *      FROM TABLE1 t1     JOIN TABLE2 t2 ON t2.col = t1.col 

But I want to warn against depending on views - if not materialized, they are only prepared SQL statements. There's no performance benefit, and can negatively impact performance if you build a view based on another. Also, views are brittle - they can change, and you won't know until using a supporting view if there are issues.

like image 103
OMG Ponies Avatar answered Oct 26 '22 03:10

OMG Ponies