SQL - Create view from multiple tables

后端 未结 4 374
被撕碎了的回忆
被撕碎了的回忆 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:26

    Are you using MySQL or PostgreSQL?

    You want to use JOIN syntax, not UNION. For example, using INNER JOIN:

    CREATE VIEW V AS
    SELECT POP.country, POP.year, POP.pop, FOOD.food, INCOME.income
    FROM POP
    INNER JOIN FOOD ON (POP.country=FOOD.country) AND (POP.year=FOOD.year)
    INNER JOIN INCOME ON (POP.country=INCOME.country) AND (POP.year=INCOME.year)
    

    However, this will only show results when each country and year are present in all three tables. If this is not what you want, look into left outer joins (using the same link above).

提交回复
热议问题