Data from two tables into one view

前端 未结 2 1188
温柔的废话
温柔的废话 2021-02-12 15:12

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.

2条回答
  •  半阙折子戏
    2021-02-12 15:22

    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.

提交回复
热议问题