I have three tables:
POP(country, year, pop)
FOOD(country, year, food)
INCOME(country, year, income)
I am trying to create a view such as:
V(country, year, pop, food, income)
This is my code so far. I don't think its correct:
CREATE VIEW V AS
(SELECT * FROM POP
UNION
SELECT * FROM FOOD
UNION
SELECT * FROM INCOME);
One issue is, a country that is present in POP
may not be present in FOOD
. Same goes for year. A year that is present in POP
may not be present in FOOD
. So, I keep thinking that the above code will not work.
A view that combines data from multiple tables enables you to show relevant information in multiple tables together. You can create a view that combines data from two or more tables by naming more than one table in the FROM clause.
Explanation: In MySQL, a 'View' can refer to multiple tables. This makes it a lot simpler to execute the queries involving joins. When a selection is made from the view, the join is executed producing the results.
The maximum number of table sources that can be joined in a single query is 256.
Answer: To do this, the SQL CREATE TABLE syntax is: CREATE TABLE new_table AS (SELECT * FROM old_table WHERE 1=2); For example: CREATE TABLE suppliers AS (SELECT * FROM companies WHERE 1=2);
This works too and you dont have to use join or anything:
DROP VIEW IF EXISTS yourview;
CREATE VIEW yourview AS
SELECT table1.column1,
table2.column2
FROM
table1, table2
WHERE table1.column1 = table2.column1;
Union is not what you want. You want to use joins to create single rows. It's a little unclear what constitutes a unique row in your tables and how they really relate to each other and it's also unclear if one table will have rows for every country in every year. But I think this will work:
CREATE VIEW V AS (
SELECT i.country,i.year,p.pop,f.food,i.income FROM
INCOME i
LEFT JOIN
POP p
ON
i.country=p.country
LEFT JOIN
Food f
ON
i.country=f.country
WHERE
i.year=p.year
AND
i.year=f.year
);
The left (outer) join will return rows from the first table even if there are no matches in the second. I've written this assuming you would have a row for every country for every year in the income table. If you don't things get a bit hairy as MySQL does not have built in support for FULL OUTER JOINs last I checked. There are ways to simulate it, and they would involve unions. This article goes into some depth on the subject: http://www.xaprb.com/blog/2006/05/26/how-to-write-full-outer-join-in-mysql/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With