MySQL CREATE VIEW targeting variable table name (columns names)

244 Views Asked by At

I want to define a lot of views but the model of the DB is changing so there are some ideas/questions that came to my mind:

  1. Is there any way in MySQL 8 to create view that after FROM has not hardcoded table name but table name is a variable?

  2. Is it possible to create view that has hardcoded name of table after FROM but column names are variable?

  3. Is it a good idea to create a view (A) that after FROM does not target a particular (hardcoded) table name but another view (B) that works as intermediate translation table that does just select data from a table (C) and gives it back to view (A) with columns aliased the way the first view (A) expects them. In short 2nd view (B) just acts as a translator between (A) <=> (C) in terms of table name and column names?

The reason I'm thinking about these solutions is I want to have a set of table views for application that connects to DB. And they should not change but the whole model of DB will change.

I don't want to touch the access views that are an interface for application but rather define some connections between columns and tables behind the app interface view. Also the DB model will need some other views to do common calculations/reporting but the source table data to calculations/reporting will be altered over time (column names, table names).

  1. Is there any other approach I could apply? How do you deal with cases of altering table names, column names in DB without breaking already implemented reporting and other functionalities that expect a particular names of tables and columns?

I'm using MySQL 8.

1

There are 1 best solutions below

0
On BEST ANSWER
  1. No
  2. No
  3. You can certainly do this and it is not uncommon to have views based on views. Whether it is a good idea, that's a matter of opinion.
  4. You cannot fully protect applications from underlying data model changes. If you introduce, remove, or change columns / columns in the data model, you must reflect them in the reports / applications, since the available content will change. If a table or column gets renamed, that can be hidden from the application through the use of views. However, if the rename is not that important so that you would reflect that in the report / application, then it begs the question why you need to rename the column.

If your data structure changes so frequently, then an SQL-based product may not be the right thing for you, since SQL requires quite rigid definition of the data structure. You may have to consider a NoSql solution instead that allows greater flexibility in the database schema. However, data structure changes will affect the application / reporting even if you use a NoSql solution.