简体   繁体   English

如何在从 mysql 中的现有表创建表时添加新的日期列

[英]how to add new date column while creating table from existing table in mysql

** I want to add date_col to new_table_name, I am trying below query but getting error ** ** 我想将 date_col 添加到 new_table_name,我正在尝试下面的查询但收到错误 **

        CREATE TABLE IF NOT EXISTS new_table_name AS
           SELECT A.employee AS employee_name,
           A.loc AS location,
           'America' country,
           date_col TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP 
           FROM existing_table_name;

The CREATE TABLE... AS SELECT... is not intended for adding new behaviors to the new table. CREATE TABLE... AS SELECT...不适用于向新表添加新行为。 Changes such as adding a default value to a column should happen in a separate ALTER statement.向列添加默认值等更改应在单独的ALTER语句中进行。 Therefore, use this approach:因此,使用这种方法:

CREATE TABLE IF NOT EXISTS new_table_name AS
SELECT employee,
       location,
       'America',
       date_col,
FROM existing_table_name;

ALTER TABLE new_table_name
MODIFY COLUMN date_col TIMESTAMP NOT NULL
DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;

If you intended those aliases to be instructions to change the column names, then you'll need ALTER statements for those too:如果您打算将这些别名用作更改列名的说明,那么您也需要ALTER语句:

ALTER TABLE new_table_name 
RENAME COLUMN employee TO employee_name;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM