How do you assign a column default in MySQL to another column's value?

a 夏天 提交于 2019-12-23 09:42:06

问题


I want to add a new column to a table in MySQL database that should get the value of another column in the same table. Is this possible? If so, how do you do it?


回答1:


Starting with MySQL 5.0.2 you can write a stored procedure linked to a TRIGGER which can examine the new column each time a row is inserted, and automatically copy the other column's value into the new column if no value was supplied for the new column.




回答2:


As of 20101212 mysql does not support defaulting 2 timestamp columns, which means you can't do a 'created' and 'updated' on the same table.

If this is what you were trying to do, then the trigger with the stored proc is the way to go.




回答3:


You Can use this following two command to do your work.

  1. This command will be used to add new column in you table. Remember data type from where you want to copy to use those data type in new Column.

    ALTER TABLE table_name ADD new_column_name VARCHAR(60);
    

2: This command to copy data from old column name to new column name.

   UPDATE table_name SET new_column_name = old_column_name;

Then if you want to delete previous column, Then you can use following command

   ALTER TABLE table_name DROP COLUMN old_column_name;



回答4:


create a view, and you can select the same column twice and give it different name, then the application can use the view instead use the table directly.



来源:https://stackoverflow.com/questions/660417/how-do-you-assign-a-column-default-in-mysql-to-another-columns-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!