root root - 3 months ago 16
MySQL Question

Is there a way to add a column into an existing view in mysql?

For a table I can do like this:

ALTER TABLE table_name
ADD column_name datatype

but this does not apply to an existing view. I wonder if there is a way to solve this?


Use the Alter View statement to edit a view. Simply use the existing SQL Statement in the current view, and add the column to the end.

More detailed explanation than the actual docs can be found here:

Edit - added

A view can only display data from an existing table. You would have to add the column to the table and then modify the view to show it as well.

Think of it this way: A view is just a way of looking at existing data in tables. Tables are holders of real data.

The only exception to the pattern above that I can think of is that you can have a column on a view that is filled with the results of a calculation such as addition or string contention. For example, consider a table with EmployeeId, FirstName and LastName columns...

You could have a view that looks like this:

Create View FullNames AS
Select EmployeeId, firstname + ' ' + lastname AS FullName from Employees

In that case, I'm sort of adding a column that doesn't exist in a table - FullName. It's a computed value based on table data. However, it's still based on data stored in teh DB somewhere.