SQL - Create view from multiple tables

后端 未结 4 370
被撕碎了的回忆
被撕碎了的回忆 2020-12-09 21:08

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:<

4条回答
  •  温柔的废话
    2020-12-09 21:34

    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/

提交回复
热议问题